#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 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录