(某培训机构的练习题)子线程循环 10 次,接着主线程循环 100 次,接着又回到子线程循环 10 次,接着再回到主线程又循环 100 次,如此循环50次,试写出代码。

从题目看,首先想到是使用条件变量来实现,以下是实现代码:

 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 *TreadFuncMa(void *arg)
10 {
11     for (int i = 0; i < 50; ++i)
12     {
13         pthread_mutex_lock(&myloack);
14 
15         if(n!=0)
16             pthread_cond_wait(&mycond,&myloack);
17 
18         for (int i = 0; i < 10; ++i)
19             cout<<"A"<<" ";
20 
21         cout<<endl;
22         n++;
23 
24         pthread_mutex_unlock(&myloack);
25         pthread_cond_broadcast(&mycond);
26     }
27     return (void *)0;
28 }
29 int  main(int argc, char const *argv[])
30 {
31     pthread_t id;
32     int ret=pthread_create(&id,NULL,TreadFuncMa,NULL);
33     if (rt!=0)
34     {
35         return 0;
36     }
37 
38     /* code */
39     for (int i = 0; i < 50; ++i)
40     {
41         pthread_mutex_lock(&myloack);
42 
43         if(n!=1)
44             pthread_cond_wait(&mycond,&myloack);
45 
46         for (int i = 0; i < 100; ++i)
47             cout<<"B"<<" ";
48 
49         cout<<endl;
50         n--;
51         
52         pthread_mutex_unlock(&myloack);
53         pthread_cond_broadcast(&mycond);
54     }
55     pthread_join(id,NULL);
56     return 0;
57 }

 

posted @ 2013-10-15 20:58  蓝夜  阅读(709)  评论(0编辑  收藏  举报