/* 线程读取循环队列*/

/* 线程读取循环队列*/

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

#define QUEUE_SIZE 5

typedef struct
{
    int data[QUEUE_SIZE];
    int front;
    int rear;
    pthread_mutex_t lock;
} CircularQueue;

void initQueue(CircularQueue *queue)
{
    queue->front = 0;
    queue->rear = 0;
    pthread_mutex_init(&queue->lock, NULL);
}

int isFull(CircularQueue *queue)
{
    return (queue->rear + 1) % QUEUE_SIZE == queue->front;
}

int isEmpty(CircularQueue *queue)
{
    return queue->front == queue->rear;
}

void enqueue(CircularQueue *queue, int value)
{
    if (!isFull(queue))
    {
        queue->data[queue->rear] = value;
        queue->rear = (queue->rear + 1) % QUEUE_SIZE;
        printf("Produced: %d\n", value);
    }
    else
    {
        printf("Queue is full!\n");
    }
}

int dequeue(CircularQueue *queue)
{
    if (!isEmpty(queue))
    {
        int value = queue->data[queue->front];
        queue->front = (queue->front + 1) % QUEUE_SIZE;
        return value;
    }
    else
    {
        return -1;
    }
}

void *producer(void *arg)
{
    CircularQueue *queue = (CircularQueue *)arg;
    while (1)
    {
        pthread_mutex_lock(&queue->lock);
        int value = rand() % 100 + 1;
        enqueue(queue, value);
        pthread_mutex_unlock(&queue->lock);
        usleep(100000);
    }
}

void *consumer(void *arg)
{
    CircularQueue *queue = (CircularQueue *)arg;
    while (1)
    {
        pthread_mutex_lock(&queue->lock);
        int value = dequeue(queue);
        pthread_mutex_unlock(&queue->lock);
        if (value != -1)
        {
            printf("Consumed: %d\n", value);
        }
        else
        {
            printf("Queue is empty!\n");
        }
        usleep(150000);
    }
}

int main(void)
{
    CircularQueue queue;
    initQueue(&queue);

    pthread_t producer_thread, consumer_thread1, consumer_thread2;
    pthread_create(&producer_thread, NULL, producer, (void *)&queue);
    pthread_create(&consumer_thread1, NULL, consumer, (void *)&queue);
    pthread_create(&consumer_thread2, NULL, consumer, (void *)&queue);
    pthread_join(producer_thread, NULL);
    pthread_join(consumer_thread1, NULL);
    pthread_join(consumer_thread2, NULL);

    pthread_mutex_destroy(&queue.lock);
    return 0;
}

posted on 2024-08-21 23:26  wessf  阅读(1)  评论(0编辑  收藏  举报