#include <unistd.h>
#include <pthread.h>
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
static int avail = 0;
//producer 一般为子线程
void producer() {
pthread_mutex_lock(&mtx);
avail++;
pthread_mutex_unlock(&mtx);
pthread_cond_signal(&cond);
}
//consunmer 一般为主线程
void consumer() {
while(1) {
pthread_mutex_lock(&mtx);
while(avail == 0) {
pthread_cond_wait(&cond, &mtx);
}
while(avail > 0) {
/* do something */
avail--;
}
pthread_mutex_unlock(&mtx);
}
}
网友评论