c语言实现LinkedBlockingQueue
时间: 2024-02-12 17:29:39 浏览: 62
linkedblockingqueue
下面是一个使用 C 语言实现的简单 LinkedBlockingQueue 的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <pthread.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
typedef struct {
Node* head;
Node* tail;
int size;
int capacity;
pthread_mutex_t mutex;
pthread_cond_t notEmpty;
pthread_cond_t notFull;
} LinkedBlockingQueue;
LinkedBlockingQueue* createQueue(int capacity) {
LinkedBlockingQueue* queue = (LinkedBlockingQueue*)malloc(sizeof(LinkedBlockingQueue));
queue->head = NULL;
queue->tail = NULL;
queue->size = 0;
queue->capacity = capacity;
pthread_mutex_init(&queue->mutex, NULL);
pthread_cond_init(&queue->notEmpty, NULL);
pthread_cond_init(&queue->notFull, NULL);
return queue;
}
void enqueue(LinkedBlockingQueue* queue, int value) {
pthread_mutex_lock(&queue->mutex);
while (queue->size == queue->capacity) {
pthread_cond_wait(&queue->notFull, &queue->mutex);
}
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = NULL;
if (queue->head == NULL) {
queue->head = newNode;
queue->tail = newNode;
} else {
queue->tail->next = newNode;
queue->tail = newNode;
}
queue->size++;
pthread_cond_signal(&queue->notEmpty);
pthread_mutex_unlock(&queue->mutex);
}
int dequeue(LinkedBlockingQueue* queue) {
pthread_mutex_lock(&queue->mutex);
while (queue->size == 0) {
pthread_cond_wait(&queue->notEmpty, &queue->mutex);
}
Node* node = queue->head;
int value = node->data;
if (queue->head == queue->tail) {
queue->head = NULL;
queue->tail = NULL;
} else {
queue->head = queue->head->next;
}
free(node);
queue->size--;
pthread_cond_signal(&queue->notFull);
pthread_mutex_unlock(&queue->mutex);
return value;
}
void destroyQueue(LinkedBlockingQueue* queue) {
pthread_mutex_destroy(&queue->mutex);
pthread_cond_destroy(&queue->notEmpty);
pthread_cond_destroy(&queue->notFull);
free(queue);
}
int main() {
LinkedBlockingQueue* queue = createQueue(5);
enqueue(queue, 1);
enqueue(queue, 2);
enqueue(queue, 3);
int value1 = dequeue(queue);
int value2 = dequeue(queue);
int value3 = dequeue(queue);
printf("Dequeued values: %d, %d, %d\n", value1, value2, value3);
destroyQueue(queue);
return 0;
}
```
这个示例代码使用了一个带有互斥锁和条件变量的结构体 LinkedBlockingQueue 来实现一个带有阻塞特性的队列。enqueue 函数用于向队列中添加元素,如果队列已满,则线程会阻塞,直到有空间可用。dequeue 函数用于从队列中取出元素,如果队列为空,则线程会阻塞,直到有元素可取。
在示例代码的主函数中,我们创建了一个容量为 5 的队列,并进行了一些入队和出队操作。最后,我们销毁了队列。
阅读全文