编写一个程序,开启3个线程,这3个线程的ID分别为A、B、C,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示;如:ABCABC….依次递推。
- #include <stdlib.h>
- #include <pthread.h>
- #include <unistd.h>
- #include <string.h>
- //#define DEBUG 1
- #define NUM 3
- int n=0;
- pthread_mutex_t mylock=PTHREAD_MUTEX_INITIALIZER;//互斥量
- pthread_cond_t qready=PTHREAD_COND_INITIALIZER;//条件变量
- void * thread_func(void *arg)
- {
- int param=(int)arg;
- char c='A'+param;
- int ret,i=0;
- for (; i < 10; i++)
- {
- pthread_mutex_lock(&mylock);
- while (param != n) //刚运行时,n = 0, param = 0,条件不成立,所以直接打印A
- {
- #ifdef DEBUG
- printf("thread %d waiting\n", param);
- #endif
- ret = pthread_cond_wait(&qready, &mylock);
- if (ret == 0)
- {
- #ifdef DEBUG
- printf("thread %d wait success\n", param);
- #endif
- } else
- {
- #ifdef DEBUG
- printf("thread %d wait failed:%s\n", param, strerror(ret));
- #endif
- }
- }
- // printf("%d ",param+1);
- printf("%c ",c);