多线程按照线程顺序打印字符

 1 #include <stdio.h>
 2 #include <pthread.h>
 3 #include <unistd.h>
 4 
 5 int num = 0;
 6 pthread_mutex_t mutex_lock = PTHREAD_MUTEX_INITIALIZER;
 7 pthread_cond_t cond_ready = PTHREAD_COND_INITIALIZER;
 8 
 9 
10 void *output_chara(void *arg)
11 {
12     int i;
13     int cond_num = (int) arg;
14 
15     for (i = 0; i < 10; i++){
16         pthread_mutex_lock(&mutex_lock);
17         while (num != cond_num){
18             pthread_cond_wait(&cond_ready, &mutex_lock);
19         }
20 
21         printf("%c", 'A' + cond_num);
22 
23         num = (num + 1) % 3;
24 
25         pthread_mutex_unlock(&mutex_lock);
26         pthread_cond_broadcast(&cond_ready);
27     }
28 }
29 
30 int main()
31 {
32     int i;
33     pthread_t tid[3];
34 
35     for (i = 0; i < 3; i++){
36         pthread_create(&tid[i], NULL, output_chara, (void *)i);
37     }
38 
39     for (i = 0; i < 3; i++){
40         pthread_join(tid[i], NULL);
41     }
42 
43     return 0;
44 }

output:

ABCABCABCABCABCABCABCABCABCABC

 

转载于:https://www.cnblogs.com/wanpengcoder/p/5344726.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值