多线程中比较常见的是生产者,消费者的模式。而实现它并不复杂,通过 pthread_mutex_lock/pthread_mutex_unlock pthread_cond_wait/pthread_cond_signal 就可以达到目的:
非常容易犯的错误是,忘记对 mutex 和 mwait 的初始化,有时候会出现非常难以发现的问题。
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t mwait;
bool exit_sign;
void init() {
pthread_mutex_init(mutex, NULL);
pthread_cond_init(mwait, NULL);
}
void relese() {
exit_sign = 1;
pthread_mutex_unlock(mutex);
pthread_cond_signal(mwait);
pthread_mutex_destroy(mutex);
pthread_cond_destroy(mwait);
}
void pushD(D *data) { pthread_mutex_lock(&D_mutex); if (D_queue.size() >= maxQueueSize) { delete (D_queue.front()); D_queue.pop();
}
D_queue.push(data); pthread_mutex_unlock(&mutex); pthread_cond_signal(&mwait); return 0; } D* popD() { pthread_mutex_lock(&mutex); D *d = NULL; while (D_queue.size() <= 0 && !exit_sign) { pthread_cond_wait(&mwait, &mutex); } if (exit_sign) { return NULL; } d = D_queue.front(); D_queue.pop(); pthread_mutex_unlock(&mutex); return d; }