(Google面试题)有四个线程1、2、3、4。线程1的功能就是输出1,线程2的功能就是输出2,以此类推.........现在有四个文件ABCD。初始都为空。



(Google面试题)有四个线程1、2、3、4。线程1的功能就是输出1,线程2的功能就是输出2,以此类推.........现在有四个文件ABCD。初始都为空。

现要让四个文件呈如下格式:

A1 2 3 4 1 2....

B2 3 4 1 2 3....

C3 4 1 2 3 4....

D4 1 2 3 4 1....

请设计程序。

 

下面举例A,对于B、C、D只是需要把修改一下全局变量n的初始化值即可:

 

 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<<"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 }
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值