生产者消费者问题代码c++
时间: 2023-10-16 15:11:12 浏览: 49
以下是一个简单的生产者消费者问题的C语言代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#define BUFFER_SIZE 8
#define PRODUCER_THREADS 2
#define CONSUMER_THREADS 2
#define NUM_ITERATIONS 10
int buffer[BUFFER_SIZE];
int count = 0; // items in buffer
int in = 0; // index for next item to be added
int out = 0; // index for next item to be removed
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t full = PTHREAD_COND_INITIALIZER;
pthread_cond_t empty = PTHREAD_COND_INITIALIZER;
void *producer(void *arg) {
for (int i = 0; i < NUM_ITERATIONS; i++) {
pthread_mutex_lock(&lock);
while (count == BUFFER_SIZE) {
pthread_cond_wait(&empty, &lock);
}
buffer[in] = rand() % 100;
++count;
in = (in + 1) % BUFFER_SIZE;
printf("Produced item %d, count = %d\n", buffer[in - 1], count);
pthread_cond_signal(&full);
pthread_mutex_unlock(&lock);
sleep(1);
}
pthread_exit(NULL);
}
void *consumer(void *arg) {
int item;
for (int i = 0; i < NUM_ITERATIONS; i++) {
pthread_mutex_lock(&lock);
while (count == 0) {
pthread_cond_wait(&full, &lock);
}
item = buffer[out];
--count;
out = (out + 1) % BUFFER_SIZE;
printf("Consumed item %d, count = %d\n", item, count);
pthread_cond_signal(&empty);
pthread_mutex_unlock(&lock);
sleep(2);
}
pthread_exit(NULL);
}
int main() {
pthread_t producers[PRODUCER_THREADS];
pthread_t consumers[CONSUMER_THREADS];
for (int i = 0; i < PRODUCER_THREADS; i++) {
pthread_create(&producers[i], NULL, producer, NULL);
}
for (int i = 0; i < CONSUMER_THREADS; i++) {
pthread_create(&consumers[i], NULL, consumer, NULL);
}
for (int i = 0; i < PRODUCER_THREADS; i++) {
pthread_join(producers[i], NULL);
}
for (int i = 0; i < CONSUMER_THREADS; i++) {
pthread_join(consumers[i], NULL);
}
return 0;
}
```
这个代码使用了线程库pthread.h中的互斥锁和条件变量来实现生产者消费者问题。其中,生产者随机生成一个0~99的整数插入到缓存区中,消费者从缓存区中取出一个整数。当缓存区已满时,生产者会等待条件empty成立;当缓存区为空时,消费者会等待条件full成立。在生产者产生一个新物品或消费者消耗一个物品时,它们会分别通知条件变量来唤醒等待的另一方。这里使用一个简单的循环缓存区来维护物品的先后顺序。