C语言中多线程的生产者和消费者模型的示例代码
时间: 2023-02-11 18:40:51 浏览: 227
这是一个 C 语言中生产者-消费者模型的示例代码:
```
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#define BUFFER_SIZE 10
int buffer[BUFFER_SIZE];
int counter = 0;
int in = 0;
int out = 0;
pthread_mutex_t mutex;
pthread_cond_t producer_cond;
pthread_cond_t consumer_cond;
void *producer(void *arg) {
while (1) {
pthread_mutex_lock(&mutex);
if (counter == BUFFER_SIZE) {
pthread_cond_wait(&producer_cond, &mutex);
}
buffer[in] = rand() % 100;
printf("Produce: %d\n", buffer[in]);
in = (in + 1) % BUFFER_SIZE;
counter++;
pthread_cond_signal(&consumer_cond);
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
void *consumer(void *arg) {
while (1) {
pthread_mutex_lock(&mutex);
if (counter == 0) {
pthread_cond_wait(&consumer_cond, &mutex);
}
printf("Consume: %d\n", buffer[out]);
out = (out + 1) % BUFFER_SIZE;
counter--;
pthread_cond_signal(&producer_cond);
pthread_mutex_unlock(&mutex);
sleep(2);
}
}
int main() {
pthread_t producer_thread, consumer_thread;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&producer_cond, NULL);
pthread_cond_init(&consumer_cond, 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(&producer_cond);
pthread_cond_destroy(&consumer_cond);
return 0;
}
```
这是一个简单的生产者-消费者模型,其中包含一个共享的缓冲区和两个线程:生产者线程和消费者线程。生产者线程不断地向缓冲区中生产随机数字,而消费者线程则不
阅读全文