溫馨提示×

如何在Linux中實現隊列的并發控制

小樊
112
2024-08-09 16:49:35
欄目: 智能運維

在Linux中,可以使用信號量或互斥鎖來實現隊列的并發控制。下面是一個簡單的示例代碼,展示如何使用互斥鎖來控制一個隊列的并發訪問:

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

#define MAX_QUEUE_SIZE 10

typedef struct {
    int queue[MAX_QUEUE_SIZE];
    int front, rear;
    pthread_mutex_t lock;
} Queue;

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

void enqueue(Queue *q, int data) {
    pthread_mutex_lock(&q->lock);

    if ((q->rear + 1) % MAX_QUEUE_SIZE == q->front) {
        printf("Queue is full\n");
    } else {
        q->queue[q->rear] = data;
        q->rear = (q->rear + 1) % MAX_QUEUE_SIZE;
    }

    pthread_mutex_unlock(&q->lock);
}

int dequeue(Queue *q) {
    int data;

    pthread_mutex_lock(&q->lock);

    if (q->front == q->rear) {
        printf("Queue is empty\n");
        data = -1;
    } else {
        data = q->queue[q->front];
        q->front = (q->front + 1) % MAX_QUEUE_SIZE;
    }

    pthread_mutex_unlock(&q->lock);

    return data;
}

int main() {
    Queue q;
    initQueue(&q);

    pthread_t producer, consumer;

    pthread_create(&producer, NULL, (void *(*)(void *))enqueue, &q);
    pthread_create(&consumer, NULL, (void *(*)(void *))dequeue, &q);

    pthread_join(producer, NULL);
    pthread_join(consumer, NULL);

    return 0;
}

在上面的示例中,一個隊列的結構體包含一個整型數組、隊列的頭尾指針以及一個互斥鎖。在enqueue和dequeue函數中,通過加鎖和解鎖互斥鎖來確保隊列的并發安全。在main函數中,創建了生產者和消費者線程來向隊列中添加元素和移除元素。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女