现在你是linux专家请使用C语言完成以下题目:使用条件变量实现生产者-消费者问题 1商品使用一个链式队列描述初始商品个数为8最大商品个数是10个不同的商品用不同的随机数区分 2生产者有3个线程每个线程每3秒产生一个商品 3 消费者有2个线程先睡眠5秒每个线程每1秒消耗一个商品 显示每次生产和消费的商品的随机编号。
以下是实现的代码,使用了pthread库和unistd库:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#define MAX_QUEUE_SIZE 10
#define PRODUCER_NUM 3
#define CONSUMER_NUM 2
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* head = NULL;
Node* tail = NULL;
int queue_size = 0;
pthread_mutex_t queue_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t queue_not_full = PTHREAD_COND_INITIALIZER;
pthread_cond_t queue_not_empty = PTHREAD_COND_INITIALIZER;
void* producer(void* arg) {
int id = *(int*)arg;
while (1) {
sleep(3);
int item = rand() % 10;
pthread_mutex_lock(&queue_mutex);
while (queue_size == MAX_QUEUE_SIZE) {
pthread_cond_wait(&queue_not_full, &queue_mutex);
}
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->data = item;
new_node->next = NULL;
if (head == NULL) {
head = new_node;
tail = new_node;
} else {
tail->next = new_node;
tail = new_node;
}
queue_size++;
printf("Producer %d produced item %d\n", id, item);
pthread_cond_signal(&queue_not_empty);
pthread_mutex_unlock(&queue_mutex);
}
return NULL;
}
void* consumer(void* arg) {
int id = *(int*)arg;
while (1) {
sleep(5);
pthread_mutex_lock(&queue_mutex);
while (queue_size == 0) {
pthread_cond_wait(&queue_not_empty, &queue_mutex);
}
int item = head->data;
Node* temp = head;
head = head->next;
free(temp);
queue_size--;
printf("Consumer %d consumed item %d\n", id, item);
pthread_cond_signal(&queue_not_full);
pthread_mutex_unlock(&queue_mutex);
sleep(1);
}
return NULL;
}
int main() {
// Initialize the queue with 8 random items
srand(time(NULL));
for (int i = 0; i < 8; i++) {
int item = rand() % 10;
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->data = item;
new_node->next = NULL;
if (head == NULL) {
head = new_node;
tail = new_node;
} else {
tail->next = new_node;
tail = new_node;
}
queue_size++;
}
// Create producer threads
pthread_t producer_threads[PRODUCER_NUM];
int producer_ids[PRODUCER_NUM];
for (int i = 0; i < PRODUCER_NUM; i++) {
producer_ids[i] = i + 1;
pthread_create(&producer_threads[i], NULL, producer, &producer_ids[i]);
}
// Create consumer threads
pthread_t consumer_threads[CONSUMER_NUM];
int consumer_ids[CONSUMER_NUM];
for (int i = 0; i < CONSUMER_NUM; i++) {
consumer_ids[i] = i + 1;
pthread_create(&consumer_threads[i], NULL, consumer, &consumer_ids[i]);
}
// Join threads
for (int i = 0; i < PRODUCER_NUM; i++) {
pthread_join(producer_threads[i], NULL);
}
for (int i = 0; i < CONSUMER_NUM; i++) {
pthread_join(consumer_threads[i], NULL);
}
return 0;
}
原文地址: https://www.cveoy.top/t/topic/bv0P 著作权归作者所有。请勿转载和采集!