用c语言实现生产者消费者问题
时间: 2023-10-21 12:05:16 浏览: 177
生产者消费者问题是一个经典的多线程同步问题,下面是一个用C语言实现的基本示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define BUFFER_SIZE 5
#define PRODUCER_NUM 2
#define CONSUMER_NUM 2
typedef struct {
int buffer[BUFFER_SIZE];
int in;
int out;
int count;
pthread_mutex_t mutex;
pthread_cond_t full;
pthread_cond_t empty;
} buffer_t;
buffer_t buffer = {
.in = 0,
.out = 0,
.count = 0,
.mutex = PTHREAD_MUTEX_INITIALIZER,
.full = PTHREAD_COND_INITIALIZER,
.empty = PTHREAD_COND_INITIALIZER
};
int produce_item() {
return rand() % 100;
}
void consume_item(int item) {
printf("Consumed item %d\n", item);
}
void *producer(void *arg) {
int item;
while (1) {
item = produce_item();
pthread_mutex_lock(&buffer.mutex);
while (buffer.count == BUFFER_SIZE) {
pthread_cond_wait(&buffer.empty, &buffer.mutex);
}
buffer.buffer[buffer.in] = item;
buffer.in = (buffer.in + 1) % BUFFER_SIZE;
buffer.count++;
pthread_cond_signal(&buffer.full);
pthread_mutex_unlock(&buffer.mutex);
printf("Produced item %d\n", item);
}
return NULL;
}
void *consumer(void *arg) {
int item;
while (1) {
pthread_mutex_lock(&buffer.mutex);
while (buffer.count == 0) {
pthread_cond_wait(&buffer.full, &buffer.mutex);
}
item = buffer.buffer[buffer.out];
buffer.out = (buffer.out + 1) % BUFFER_SIZE;
buffer.count--;
pthread_cond_signal(&buffer.empty);
pthread_mutex_unlock(&buffer.mutex);
consume_item(item);
}
return NULL;
}
int main() {
pthread_t producers[PRODUCER_NUM];
pthread_t consumers[CONSUMER_NUM];
int i;
for (i = 0; i < PRODUCER_NUM; i++) {
pthread_create(&producers[i], NULL, producer, NULL);
}
for (i = 0; i < CONSUMER_NUM; i++) {
pthread_create(&consumers[i], NULL, consumer, NULL);
}
for (i = 0; i < PRODUCER_NUM; i++) {
pthread_join(producers[i], NULL);
}
for (i = 0; i < CONSUMER_NUM; i++) {
pthread_join(consumers[i], NULL);
}
return 0;
}
```
在该示例中,buffer_t是一个缓冲区结构体,包含一个固定大小的缓冲区、入队和出队指针、当前缓冲区中的元素个数以及互斥锁和条件变量等同步机制。produce_item()和consume_item()分别表示生产和消费一个元素的函数。producer()和consumer()是两个线程函数,分别表示生产者和消费者的行为。在生产者线程中,如果缓冲区已满,则线程将等待直到有空间可用。当元素被生产并插入缓冲区后,线程会通知消费者线程消费元素。在消费者线程中,如果缓冲区为空,则线程将等待直到有元素可用。当元素被消费后,线程会通知生产者线程生产更多的元素。最后,在main()函数中,创建多个生产者和消费者线程,并等待它们完成。
阅读全文