多线程按照线程顺序打印字符
Posted Alex
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程按照线程顺序打印字符相关的知识,希望对你有一定的参考价值。
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
以上是关于多线程按照线程顺序打印字符的主要内容,如果未能解决你的问题,请参考以下文章
多线程编程——面试题,每个线程只打印一种字符,多个线程协同顺序打印n次字符串(求大神的其他实现方案)