1024programmer Java (Google interview question) There are four threads 1, 2, 3, and 4. The function of thread 1 is to output 1, the function of thread 2 is to output 2, and so on… There are now four files ABCD. Initially they are empty.

(Google interview question) There are four threads 1, 2, 3, and 4. The function of thread 1 is to output 1, the function of thread 2 is to output 2, and so on… There are now four files ABCD. Initially they are empty.

Now we want the four files to be in the following format:

A1 2 3 4 1 2….

B2 3 4 1 2 3….

C3 4 1 2 3 4….

D4 1 2 3 4 1….

Please design a program.

The following is an example of A. For B, C, and D, you only need to modify the initialization value of the global variable n:

 1 #include 
  2 #include 
  3 #include 
  4 using namespace std;
 5
  6 pthread_mutex_t myloack=PTHREAD_MUTEX_INITIALIZER;
  7 pthread_cond_t mycOnd=PTHREAD_COND_INITIALIZER;
  8 int n=0;
  9 void *ThreadFunc(void *arg)
 10 {
 11 int num=(int )arg;
 12 for (int i = 0; i <10  ; ++i)
 13  {
 14 pthread_mutex_lock(&myloack);
 15 while (n!=num)
 16 pthread_cond_wait(&mycond,&myloack);
 17
 18 if (num==0)
 19 cout<<"1";
 20 else if(num==1)
 21 cout<<"2";
 22 else if(num==2)
 23 cout<<"3";
 24 else
 25 cout<<"4"<<endl;
 26 n=(n+1)%4;
 27 pthread_mutex_unlock(&myloack);
 28 pthread_cond_broadcast(&mycond);
 29  }
 30 return (void *)0;
 31 }
 32
 33 int main(int argc, char const *argv[  ])
 34 {
 35
 36 pthread_t id[4];
 37 for (int i = 0; i <4  ; ++i)
 38  {
 39 int err=pthread_create(&id[i],NULL,ThreadFunc,(void *)i);
 40 if (err!=0)
 41  {
 42 cout<<"create err:"<<endl;
 43 exit(-1);
 44  }
 45
 46  }
 47
 48 for (int i = 0; i <4; ++i)
 49  {
 50 int ret=pthread_join(id[i],NULL);
 51 if (ret!=0)
 52  {
 53 cout<<"join err:"<<endl;
 54 exit(-1);
 55  }
 56  }
 57 return 0;
 58 }

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/756930

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索