生产者消费者问题c++代码
时间: 2023-10-02 18:07:54 浏览: 111
以下是一个简单的生产者消费者问题的C代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define BUFFER_SIZE 10
pthread_mutex_t mutex;
pthread_cond_t buffer_not_full;
pthread_cond_t buffer_not_empty;
int buffer[BUFFER_SIZE];
int counter;
void *producer(void *arg) {
int item = 0;
while (1) {
pthread_mutex_lock(&mutex);
while (counter == BUFFER_SIZE) {
pthread_cond_wait(&buffer_not_full, &mutex);
}
buffer[counter++] = item;
printf("Producer produced %d\n", item++);
pthread_cond_signal(&buffer_not_empty);
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
void *consumer(void *arg) {
int item;
while (1) {
pthread_mutex_lock(&mutex);
while (counter == 0) {
pthread_cond_wait(&buffer_not_empty, &mutex);
}
item = buffer[--counter];
printf("Consumer consumed %d\n", item);
pthread_cond_signal(&buffer_not_full);
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
int main() {
pthread_t producer_thread, consumer_thread;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&buffer_not_full, NULL);
pthread_cond_init(&buffer_not_empty, NULL);
pthread_create(&producer_thread, NULL, producer, NULL);
pthread_create(&consumer_thread, NULL, consumer, NULL);
pthread_join(producer_thread, NULL);
pthread_join(consumer_thread, NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&buffer_not_full);
pthread_cond_destroy(&buffer_not_empty);
return 0;
}
```
阅读全文