#include <stdio.h> #include <sys/types.h> #include <stdlib.h> #include <pthread.h> struct stu_t{ int dowait; pthread_cond_t cond; pthread_mutex_t mutex; }; struct stu_t stu; void* do_send(void* args){ pthread_mutex_lock(&(stu.mutex)); printf("do send get the locki\n"); if(stu.dowait==0){ printf("do send before send signal\n"); stu.dowait=1; pthread_cond_signal(&(stu.cond)); printf("do send after send signal\n"); } pthread_mutex_unlock(&(stu.mutex)); printf("end of send signal\n"); } void* do_wait(void *args){ pthread_mutex_lock(&(stu.mutex)); printf("do wait get the lock\n"); while(stu.dowait==0) { printf("dowait before cond wait\n"); pthread_cond_wait(&(stu.cond),&(stu.mutex)); printf("dowait after cond wait\n"); } printf("*************************"); stu.dowait==0; // do other other things printf("#####################"); pthread_mutex_unlock(&(stu.mutex)); } int main(){ pthread_t tid1,tid2; stu.dowait=0; pthread_mutex_init(&(stu.mutex),NULL); pthread_cond_init(&(stu.cond),NULL); pthread_create(&tid1,NULL,do_wait,NULL); pthread_create(&tid2,NULL,do_send,NULL); sleep(3); }
示例代码。
PS在do_send中unlock和signal调用顺序任意都可以。