无锁队列的C代码

标签 c queue lock-free

如何在 C 中实现这个无锁队列伪代码?

ENQUEUE(x)
    q ← new record
    q^.value ← x
    q^.next ← NULL
    repeat
        p ← tail
        succ ← COMPARE&SWAP(p^.next, NULL, q)
        if succ ≠ TRUE
            COMPARE&SWAP(tail, p, p^.next)
    until succ = TRUE
    COMPARE&SWAP(tail,p,q)
end

DEQUEUE()
    repeat
        p ← head
        if p^.next = NULL
            error queue empty
    until COMPARE&SWAP(head, p, p^.next)
    return p^.next^.value
end

如何使用 Built-in functions for atomic memory access

__sync_bool_compare_and_swap (type *ptr, type oldval type newval, ...)

我现在有

typedef struct queueelem {
    queuedata_t data;
    struct queueelem *next;
} queueelem_t;

typedef struct queue {
    int capacity;
    int size;
    queueelem_t *head;
    queueelem_t *tail;
} queue_t;

queue_t *
queue_init(int capacity)
{
    queue_t *q = (queue_t *) malloc(sizeof(queue_t));
    q->head = q->tail = NULL;
    q->size = 0;
    q->capacity = capacity;
    return q;
}

最佳答案

https://www.liblfds.org/

公共(public)领域、无许可证、可移植的 C 无锁算法实现。

为 Windows 和 Linux 开箱即用。

在 Linux 上使用 GCC,因此使用内部函数(好吧,除了 128 位 CAS 之外,没有内部函数 - 为此使用内联汇编)。

包含 M&S 队列。查看源代码,看看它是如何完成的。

关于无锁队列的C代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6092262/

相关文章:

c - C语言中如何将long int转换为int

java - 如何根据时间或特定数量后处理事件

python - Python 的通用优先级队列

c++ - 尝试实现无锁队列时发生堆栈溢出

c - 如何在C中动态初始化二维数组?

c - 如何更改 objdump 输出格式?

c - Fclose 导致 C 中的段错误

java - 处理可能出现时间关键错误的异步保存?

c++ - 人们实际上使用什么无锁原语在c++中进行无锁音频处理?

c - 如何在 C 中实现无锁共享标志?