第四题(迅雷笔试题):编写一个程序,开启3个线程,这3个线程的ID分别为A、B、C,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示;如:ABCABC….依次递推。

 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 }

 

posted @ 2013-10-15 21:27  蓝夜  阅读(2405)  评论(0编辑  收藏  举报