条件变量实现生产者消费者模型
一个生产者一个消费者模型
#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <deque>
using namespace std;
deque<int> msg;
pthread_cond_t has_product = PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
void* consumer(void *p) {
srand(time(0));
for (;;) {
pthread_mutex_lock(&lock);
while (msg.size() == 0) {
pthread_cond_wait(&has_product, &lock);
}
cout << "Consume:" << msg.front() << endl;
msg.pop_front();
pthread_mutex_unlock(&lock);
sleep(rand() % 10);
}
}
void* producer(void *p) {
srand(time(0));
for (;;) {
int product = rand() % 10000;
pthread_mutex_lock(&lock);
msg.push_back(product);
cout << "Produce:" << product << endl;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&has_product);
sleep(rand() % 5);
}
}
int main(int argc, char *argv[]) {
pthread_t pid;
pthread_t cid;
pthread_create(&pid, nullptr, producer, nullptr);
pthread_create(&cid, nullptr, consumer, nullptr);
pthread_join(pid, nullptr);
pthread_join(cid, nullptr);
return 0;
}