注意要点:
进入pthread_cond_wait之前必须加互斥锁,以防止多线程同时请求pthread_cond_wait。
在进入pthread_cond_wait后等待时,该函数会将互斥锁解锁。
在离开pthread_cond_wait前,又会从新加锁。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define THREAD_NUM 3
static unsigned int g_num = 0;
static pthread_t g_tarr[THREAD_NUM];
static pthread_cond_t g_cond;
static pthread_mutex_t g_mutex;
void* thn_t (void *arg) {
int num = (int)arg;
char var = 'a'+num;
int i;
printf ("var = %c\n", var);
for ( ; ; ) {
pthread_mutex_lock (&g_mutex);
if (g_num % THREAD_NUM != num) {
pthread_cond_wait (&g_cond, &g_mutex);
}
printf ("%c\n", var);
g_num++;
pthread_mutex_unlock (&g_mutex);
pthread_cond_broadcast (&g_cond);
sleep (1);
}
}
int main (void) {
int i;
void *ret;
pthread_mutex_init (&g_mutex,0);
pthread_cond_init (&g_cond,0);
for (i = 0; i < THREAD_NUM; ++i) {
pthread_create (&g_tarr[i],0,thn_t,(void*)i);
}
pthread_join (g_tarr[THREAD_NUM-1],&ret);
return 0;
}