在C語言中,處理多線程通常需要使用線程庫(kù),如POSIX線程(pthread)庫(kù)。下面是一個(gè)簡(jiǎn)單的示例,展示了如何使用pthread庫(kù)創(chuàng)建多個(gè)線程并執(zhí)行隊(duì)列操作。
首先,確保你的系統(tǒng)支持pthread庫(kù)。然后,創(chuàng)建一個(gè)名為queue.h
的頭文件,用于定義隊(duì)列結(jié)構(gòu)和相關(guān)的函數(shù)原型:
#ifndef QUEUE_H
#define QUEUE_H
typedef struct {
int *data;
int front;
int rear;
int size;
int capacity;
} Queue;
Queue* createQueue(int capacity);
void enqueue(Queue *queue, int item);
int dequeue(Queue *queue);
int isFull(Queue *queue);
int isEmpty(Queue *queue);
#endif
接下來,創(chuàng)建一個(gè)名為queue.c
的文件,用于實(shí)現(xiàn)隊(duì)列結(jié)構(gòu)和相關(guān)的函數(shù):
#include <stdio.h>
#include <stdlib.h>
#include "queue.h"
Queue* createQueue(int capacity) {
Queue *queue = (Queue *)malloc(sizeof(Queue));
queue->capacity = capacity;
queue->front = queue->size = 0;
queue->rear = capacity - 1;
queue->data = (int *)malloc(queue->capacity * sizeof(int));
return queue;
}
void enqueue(Queue *queue, int item) {
if (isFull(queue)) {
printf("Queue is full\n");
return;
}
queue->rear = (queue->rear + 1) % queue->capacity;
queue->data[queue->rear] = item;
queue->size = queue->size + 1;
}
int dequeue(Queue *queue) {
if (isEmpty(queue)) {
printf("Queue is empty\n");
return -1;
}
int item = queue->data[queue->front];
queue->front = (queue->front + 1) % queue->capacity;
queue->size = queue->size - 1;
return item;
}
int isFull(Queue *queue) {
return (queue->size == queue->capacity);
}
int isEmpty(Queue *queue) {
return (queue->size == 0);
}
然后,創(chuàng)建一個(gè)名為main.c
的文件,用于創(chuàng)建多個(gè)線程并執(zhí)行隊(duì)列操作:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include "queue.h"
Queue *queue;
pthread_mutex_t lock;
void *producer(void *arg) {
for (int i = 1; i <= 10; i++) {
pthread_mutex_lock(&lock);
enqueue(queue, i);
printf("Produced: %d\n", i);
pthread_mutex_unlock(&lock);
}
return NULL;
}
void *consumer(void *arg) {
for (int i = 0; i < 10; i++) {
pthread_mutex_lock(&lock);
int item = dequeue(queue);
printf("Consumed: %d\n", item);
pthread_mutex_unlock(&lock);
}
return NULL;
}
int main() {
queue = createQueue(5);
pthread_t producerThread, consumerThread;
pthread_mutex_init(&lock, NULL);
pthread_create(&producerThread, NULL, producer, NULL);
pthread_create(&consumerThread, NULL, consumer, NULL);
pthread_join(producerThread, NULL);
pthread_join(consumerThread, NULL);
pthread_mutex_destroy(&lock);
free(queue->data);
free(queue);
return 0;
}
在這個(gè)示例中,我們創(chuàng)建了一個(gè)具有5個(gè)元素的隊(duì)列,并使用兩個(gè)線程分別執(zhí)行生產(chǎn)者(producer)和消費(fèi)者(consumer)操作。我們使用互斥鎖(pthread_mutex_t)來確保在多線程環(huán)境下對(duì)隊(duì)列的安全訪問。
要編譯和運(yùn)行此示例,請(qǐng)使用以下命令:
gcc -o main main.c queue.c -lpthread
./main
這將輸出生產(chǎn)者和消費(fèi)者線程交替執(zhí)行的隊(duì)列操作。