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

 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