#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
int cnt = 0;
void* fun1(void* argv){
fprintf(stdout, "enter fun1\n");
pthread_mutex_lock(&mutex);
while(cnt < 10){
//执行下面的语句后,mutex会被释放,可以供其他的线程使用
pthread_cond_wait(&cond, &mutex);
}
fprintf(stdout, "cnt is %d\n", cnt);
pthread_mutex_unlock(&mutex);
fprintf(stdout, "leave fun1\n");
}
void* fun2(void* argv){
fprintf(stdout, "enter fun2\n");
pthread_mutex_lock(&mutex);
cnt = 10;
//唤醒被cond阻塞的线程
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
fprintf(stdout, "leave fun2\n");
}
int main(){
int ret;
if(( ret = pthread_mutex_init(&mutex, NULL)) != 0){
fprintf(stderr, "initialize mutex error. msg:%s\n", strerror(ret));
}
if(( ret = pthread_cond_init(&cond, NULL)) != 0){
fprintf(stderr, "initialize cond error. msg:%s\n", strerror(ret));
}
pthread_t p1, p2;
if((ret = pthread_create(&p2, NULL, fun2, NULL))){
fprintf(stderr, "create thread 2 error\n");
}
if((ret = pthread_create(&p1, NULL, fun1, NULL))){
fprintf(stderr, "create thread 1 error\n");
}
pthread_join(p1, NULL);
pthread_join(p2, NULL);
return 0;
}