使用多线程交替打印ABC十次

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36474990/article/details/82951128

这道题在我面试的时候被问到过。

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

使用锁可以实现该功能。

猜你喜欢

转载自blog.csdn.net/qq_36474990/article/details/82951128