基于C语言实现无锁队列
时间: 2023-04-10 15:04:49 浏览: 342
非常感谢您的提问!以下是基于C语言实现无锁队列的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdatomic.h>
typedef struct node {
void* data;
struct node* next;
} node_t;
typedef struct queue {
_Atomic(node_t*) head;
_Atomic(node_t*) tail;
} queue_t;
void queue_init(queue_t* q) {
node_t* sentinel = malloc(sizeof(node_t));
sentinel->next = NULL;
q->head = q->tail = sentinel;
}
void queue_push(queue_t* q, void* data) {
node_t* node = malloc(sizeof(node_t));
node->data = data;
node->next = NULL;
node_t* prev_tail = atomic_exchange(&q->tail, node);
atomic_store(&prev_tail->next, node);
}
void* queue_pop(queue_t* q) {
node_t* head = atomic_load(&q->head);
node_t* first = atomic_load(&head->next);
if (first == NULL) {
return NULL;
}
void* data = first->data;
atomic_store(&q->head, first);
free(head);
return data;
}
```
希望这个代码示例能够帮助您实现无锁队列。如果您有任何其他问题,请随时问我!
阅读全文