生产者消费者问题C语言代码
时间: 2023-11-12 22:21:48 浏览: 89
C语言编程模拟生产者和消费者问题(附代码程序).pdf
5星 · 资源好评率100%
以下是一个简单的生产者消费者问题的C语言代码:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define BUFFER_SIZE 10
int buffer[BUFFER_SIZE];
int in = 0, out = 0;
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 i;
for (i = 1; i <= 20; i++) {
pthread_mutex_lock(&mutex);
while (count == BUFFER_SIZE) {
pthread_cond_wait(&empty, &mutex);
}
buffer[in] = i;
printf("Producer produces the item %d : buffer[%d]\n", buffer[in], in);
in = (in + 1) % BUFFER_SIZE;
count++;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&full);
}
return NULL;
}
void *consumer(void *arg) {
int i;
int item;
for (i = 1; i <= 20; i++) {
pthread_mutex_lock(&mutex);
while (count == 0) {
pthread_cond_wait(&full, &mutex);
}
item = buffer[out];
printf("Consumer consumes the item %d : buffer[%d]\n", item, out);
out = (out + 1) % BUFFER_SIZE;
count--;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&empty);
}
return NULL;
}
int main() {
pthread_t producer_tid, consumer_tid;
pthread_create(&producer_tid, NULL, producer, NULL);
pthread_create(&consumer_tid, NULL, consumer, NULL);
pthread_join(producer_tid, NULL);
pthread_join(consumer_tid, NULL);
return 0;
}
注意:本代码只是一个简单的示例,实际上在生产者消费者问题中,还需要考虑到线程安全、死锁等问题。如果需要使用本代码,请根据具体情况进行适当的修改和完善。
阅读全文