/*
多个线程保序输出 开启3个线程,这3个线程的ID分别为A、B、C,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示; 如:ABCABC….依次递推。 */#include <stdio.h>
#include <stdlib.h> #include <pthread.h> #include <unistd.h> #include <string.h>#define DEBUG 1
int num = 0;
pthread_mutex_t mylock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t qready=PTHREAD_COND_INITIALIZER;void* thread_func1(void *arg)
{ int param = *(int*) arg; int i; for(i = 0; i < 10; i++) { pthread_mutex_lock(&mylock); while(param != num) pthread_cond_wait(&qready, &mylock); printf("%c", param + 'A'); num = (num + 1) % 3; pthread_mutex_unlock(&mylock); pthread_cond_broadcast(&qready); } return (void *)0; }int main()
{ int i; pthread_t tid[3]; int work[3]; void *tret; for(i = 0; i < 3; i++){ work[i] = i; pthread_create(&tid[i], NULL, thread_func1, (void *) &work[i]); } for(i = 0; i < 3; i++) pthread_join(tid[i], &tret);return 0;
}