1 #include <iostream>
 2 #include <stdlib.h>
 3 #include <pthread.h>
 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<<"A";
20         else if(num==1)
21             cout<<"B";
22         else
23             cout<<"C"<<endl;
24         n=(n+1)%3;
25         pthread_mutex_unlock(&myloack);
26         pthread_cond_broadcast(&mycond);
27     }
28     return (void *)0;
29 }
30 int  main(int argc, char const *argv[])
31 {
32     pthread_t id[3];
33     for (int i = 0; i < 3; ++i)
34     {
35         int err=pthread_create(&id[i],NULL,ThreadFunc,(void *)i);
36         if (err!=0)
37         {
38             cout<<"create err:"<<endl;
39             exit(-1);
40         }
41 
42     }
43 
44     for (int i = 0; i < 3; ++i)
45     {
46         int ret=pthread_join(id[i],NULL);
47         if (ret!=0)
48         {
49             cout<<"join err:"<<endl;
50             exit(-1);
51         }
52     }
53     return 0;
54 }

 

相关文章:

  • 2022-02-21
  • 2022-12-23
  • 2022-03-09
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-12-26
  • 2021-07-26
  • 2021-10-14
  • 2022-01-26
  • 2021-07-22
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案