生产者和消费者进程的同步与互斥 c语言代码
时间: 2023-10-11 13:07:46 浏览: 79
以下是一个简单的生产者和消费者进程同步和互斥的 C 语言代码:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define BUFFER_SIZE 5 // 缓冲区大小
#define PRODUCER_NUM 5 // 生产者数量
#define CONSUMER_NUM 5 // 消费者数量
#define ITEM_NUM 20 // 生产者和消费者的要生产或要消费的物品数量
pthread_mutex_t mutex; // 互斥锁
pthread_cond_t full, empty; // 条件变量
int buffer[BUFFER_SIZE]; // 缓冲区数组
int in = 0, out = 0; // 生产者和消费者在缓冲区数组中的位置
int item_produced = 0; // 当前已生产的物品数量
int item_consumed = 0; // 当前已消费的物品数量
void* producer(void *arg) // 生产者线程函数
{
int id = *(int*)arg;
while (item_produced < ITEM_NUM) {
int item = rand() % 100 + 1;
pthread_mutex_lock(&mutex);
while ((in + 1) % BUFFER_SIZE == out)
pthread_cond_wait(&empty, &mutex);
buffer[in] = item;
printf("Producer %d produced item %d.\n", id, item);
in = (in + 1) % BUFFER_SIZE;
item_produced++;
pthread_cond_signal(&full);
pthread_mutex_unlock(&mutex);
}
printf("Producer %d finished.\n", id);
pthread_exit(NULL);
}
void* consumer(void *arg) // 消费者线程函数
{
int id = *(int*)arg;
while (item_consumed < ITEM_NUM) {
pthread_mutex_lock(&mutex);
while (in == out)
pthread_cond_wait(&full, &mutex);
int item = buffer[out];
printf("Consumer %d consumed item %d.\n", id, item);
out = (out + 1) % BUFFER_SIZE;
item_consumed++;
pthread_cond_signal(&empty);
pthread_mutex_unlock(&mutex);
}
printf("Consumer %d finished.\n", id);
pthread_exit(NULL);
}
int main()
{
srand(time(NULL));
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&full, NULL);
pthread_cond_init(&empty, NULL);
pthread_t producers[PRODUCER_NUM], consumers[CONSUMER_NUM];
int producer_ids[PRODUCER_NUM], consumer_ids[CONSUMER_NUM];
for (int i = 0; i < PRODUCER_NUM; i++) {
producer_ids[i] = i+1;
pthread_create(&producers[i], NULL, producer, &producer_ids[i]);
}
for (int i = 0; i < CONSUMER_NUM; i++) {
consumer_ids[i] = i+1;
pthread_create(&consumers[i], NULL, consumer, &consumer_ids[i]);
}
for (int i = 0; i < PRODUCER_NUM; i++)
pthread_join(producers[i], NULL);
for (int i = 0; i < CONSUMER_NUM; i++)
pthread_join(consumers[i], NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&full);
pthread_cond_destroy(&empty);
return 0;
}
请注意,此代码并非完美的同步和互斥实现,其他实现也可以正常工作。如果您需要更详细的解释,请让我知道。