给条件信号发送信号代码:
pthread_mutex_lock(&mutex); while (条件为真); pthread_cond_signal(cond, mutex); 修改条件 pthread_mutex_unlock(&mutex); 细节问题 pthread_cond_wait(&cond, &mutex); 内部完成了三件事: 1. 对mutex进行解锁;2,等待条件,直到有线程向它发起通知;3,重新对mutex进行加锁。 pthread_cond_signal(&cond); 向第一个等待条件的线程发起通知,如果没有任何一个线程处于等待条件的状态,这个通知将被忽略。为什么检测条件用while而不是if?因为pthread_cond_wait会产生信号,有两种情况,一种是pthread_cond_wait会自动重启,好像这个信号没有发生一样,第二种pthread_cond_wait可能会被虚假唤醒,因此还需要重新判断。
#include<pthread.h> #include<unistd.h> #include<stdio.h> #include<sys/types.h> #include<stdlib.h> #include<errno.h> #include<string.h> #include<semaphore.h> #include <fcntl.h> /* For O_* constants */ #include <sys/stat.h> #define ERR_EXIT(m) do{perror(m);exit(EXIT_FAILURE);}while(0) #define CONSUMER_COUNT 2 #define PRODUCER_COUNT 1 pthread_cond_t g_cond; pthread_mutex_t g_mutex; pthread_t g_thread[CONSUMER_COUNT+PRODUCER_COUNT]; int nready=0;// void* consume(void *arg) { int n=(int)((long)arg); while(1) { pthread_mutex_lock(&g_mutex); while(nready==0) { printf("%d consuer begin wait\n",n); pthread_cond_wait(&g_cond,&g_mutex); } printf("%d end wait a condtion...\n",n); printf("%d begin consume\n",n); --nready; printf("%d end consume\n",n); pthread_mutex_unlock(&g_mutex); sleep(1); } return NULL; } void* produce(void *arg) { int n=(int)((long)arg); while(1) { pthread_mutex_lock(&g_mutex); printf("%d begin produce\n",n); ++nready; printf("%d end produce\n",n); printf("%d signal ....\n",n); pthread_cond_signal(&g_cond); pthread_mutex_unlock(&g_mutex); sleep(5); } return NULL; } int main() { pthread_cond_init(&g_cond,NULL); pthread_mutex_init(&g_mutex,NULL); int i=0; for(i=0;i<CONSUMER_COUNT;i++) { pthread_create(&g_thread[i],NULL,consume,(void*)((long) i)); } sleep(2); for(i=0;i<PRODUCER_COUNT;i++) { pthread_create(&g_thread[i+CONSUMER_COUNT],NULL,produce,(void*)((long) i)); } for(i=0;i<CONSUMER_COUNT+PRODUCER_COUNT;i++)pthread_join(g_thread[i],NULL); pthread_mutex_destroy(&g_mutex); pthread_cond_destroy(&g_cond); }