生产者消费者问题C语言代码
时间: 2023-11-12 16:12:00 浏览: 56
以下是一个简单的生产者消费者问题的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define BUFFER_SIZE 10
int buffer[BUFFER_SIZE];
int count = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t full = PTHREAD_COND_INITIALIZER;
pthread_cond_t empty = PTHREAD_COND_INITIALIZER;
void *producer(void *arg)
{
int item, i;
for (i = 0; i < 20; i++) {
item = rand() % 100;
pthread_mutex_lock(&mutex);
if (count == BUFFER_SIZE) {
pthread_cond_wait(&empty, &mutex);
}
buffer[count] = item;
printf("Producer produced %d\n", item);
count++;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&full);
}
pthread_exit(NULL);
}
void *consumer(void *arg)
{
int item, i;
for (i = 0; i < 20; i++) {
pthread_mutex_lock(&mutex);
if (count == 0) {
pthread_cond_wait(&full, &mutex);
}
item = buffer[count - 1];
printf("Consumer consumed %d\n", item);
count--;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&empty);
}
pthread_exit(NULL);
}
int main()
{
pthread_t tid1, tid2;
srand(time(NULL));
pthread_create(&tid1, NULL, producer, NULL);
pthread_create(&tid2, NULL, consumer, NULL);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
return 0;
}
```
该代码创建了两个线程,一个是生产者,另一个是消费者。生产者每次生产一个随机数,存放到buffer中,每次生产后调用pthread_cond_signal(&full)唤醒等待在full条件变量上的消费者线程。如果buffer已满,则等待在empty条件变量上,等待消费者消费。消费者每次从buffer中取出一个随机数,如果buffer为空则等待在full条件变量上,等待生产者生产。每次消费后调用pthread_cond_signal(&empty)唤醒等待在empty条件变量上的生产者线程。
阅读全文