现在你是linux专家请用C语言完成以下题目使用条件变量实现生产者-消费者问题 1商品使用一个链式队列描述初始商品个数为8最大商品个数是10个不同的商品用不同的随机数区分 2生产者有3个线程每个线程每3秒产生一个商品 3 消费者有2个线程先睡眠5秒每个线程每1秒消耗一个商品 显示每次生产和消费的商品的随机编号。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define MAX_SIZE 10
#define PRODUCER_NUM 3
#define CONSUMER_NUM 2
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t empty = PTHREAD_COND_INITIALIZER;
pthread_cond_t full = PTHREAD_COND_INITIALIZER;
typedef struct Node {
int data;
struct Node *next;
} Node;
Node *head = NULL, *tail = NULL;
int size = 0;
void enqueue(int data) {
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (tail == NULL) {
head = tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
size++;
}
int dequeue() {
if (head == NULL) {
return -1;
}
Node *temp = head;
int data = temp->data;
if (head == tail) {
head = tail = NULL;
} else {
head = head->next;
}
free(temp);
size--;
return data;
}
void* producer(void* arg) {
int id = *(int*)arg;
while (1) {
pthread_mutex_lock(&mutex);
while (size == MAX_SIZE) {
pthread_cond_wait(&empty, &mutex);
}
int data = rand() % 10;
printf("producer %d produces %d\n", id, data);
enqueue(data);
pthread_cond_signal(&full);
pthread_mutex_unlock(&mutex);
sleep(3);
}
return NULL;
}
void* consumer(void* arg) {
int id = *(int*)arg;
while (1) {
pthread_mutex_lock(&mutex);
while (size == 0) {
pthread_cond_wait(&full, &mutex);
}
int data = dequeue();
printf("consumer %d consumes %d\n", id, data);
pthread_cond_signal(&empty);
pthread_mutex_unlock(&mutex);
sleep(1);
}
return NULL;
}
int main() {
srand(time(NULL));
for (int i = 0; i < 8; i++) {
int data = rand() % 10;
enqueue(data);
}
pthread_t producerThreads[PRODUCER_NUM];
int producerIds[PRODUCER_NUM];
for (int i = 0; i < PRODUCER_NUM; i++) {
producerIds[i] = i + 1;
pthread_create(&producerThreads[i], NULL, producer, &producerIds[i]);
}
pthread_t consumerThreads[CONSUMER_NUM];
int consumerIds[CONSUMER_NUM];
for (int i = 0; i < CONSUMER_NUM; i++) {
consumerIds[i] = i + 1;
pthread_create(&consumerThreads[i], NULL, consumer, &consumerIds[i]);
}
for (int i = 0; i < PRODUCER_NUM; i++) {
pthread_join(producerThreads[i], NULL);
}
for (int i = 0; i < CONSUMER_NUM; i++) {
pthread_join(consumerThreads[i], NULL);
}
return 0;
}
原文地址: https://www.cveoy.top/t/topic/bvWf 著作权归作者所有。请勿转载和采集!