多线程生产者和消费者的同步和互斥问题
定义缓冲区大小为10,三个生产者线程,两个消费者线程,linux下利用互斥和状态变量实现生产者和消费者模型
c++代码
#include <pthread.h>
#include <queue>
#include <stdio.h>
#include <unistd.h>
using namespace std;
#define MAX_MSG_LEN 10
pthread_mutex_t mutex;
pthread_cond_t condvar_p, condvar_c;
queue<int> msgQueue;
void *producer(void *args)
{
int threadid = *(int*)args;
for (int i = 0; i < 10; ++i) {
usleep(10 * 1000);
// try to consume a box
pthread_mutex_lock(&mutex);
if (msgQueue.size() >= MAX_MSG_LEN) {
pthread_cond_wait(&condvar_c, &mutex);
}
// produce a product
printf("Thread %d Produce message %d\n", threadid, i);
msgQueue.push(i);
pthread_mutex_unlock(&mutex);
// signal consumer threads
pthread_cond_signal(&condvar_p);
}
pthread_exit((void *)0);
return NULL;
}
void *consumer(void *args)
{
int threadid = *(int *)args;
// usleep(10*1000);
while (true) {
// usleep(10 * 1000);
pthread_mutex_lock(&mutex);
if (msgQueue.size() <= 0) {
pthread_cond_wait(&condvar_p, &mutex);
}
if (msgQueue.size() > 0) {
printf("Thread %d consume message %d\n", threadid, msgQueue.front());
msgQueue.pop();
}
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&condvar_c);
}
pthread_exit((void *)0);
return NULL;
}
int main()
{
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&condvar_p, NULL);
pthread_cond_init(&condvar_c, NULL);
pthread_t producer1, producer2, producer3, consumer1, consumer2;
int i = 1, j = 2, k = 3, l = 4, m = 5;
pthread_create(&producer1, NULL, producer, (void*)&i);
pthread_create(&producer2, NULL, producer, (void*)&j);
pthread_create(&producer3, NULL, producer, (void*)&k);
pthread_create(&consumer1, NULL, consumer, (void*)&l);
pthread_create(&consumer2, NULL, consumer, (void*)&m);
pthread_join(producer1, NULL);
pthread_join(producer2, NULL);
pthread_join(producer3, NULL);
pthread_join(consumer1, NULL);
pthread_join(consumer2, NULL);
return 0;
}
编译命令
g++ main.cpp -std=c++11 -o out -lpthread
附注
可以通过取消代码中的注释,模拟生产者或消费者中的一类或多类线程 阻塞或低效运行时,同步和互斥的作用效果