原子操作与无锁编程:用 _Atomic 构建无锁数据结构
C11 原子类型(_Atomic)结合 memory_order 定义,实现无锁队列与引用计数,避免互斥锁的开销与死锁风险。 · 难度:入门 · +10XP
原子操作与无锁编程:用 _Atomic 构建无锁数据结构
C11 标准库
#include <stdatomic.h>
struct Node {
int value;
_Atomic(struct Node*) next;
};
void push(_Atomic(struct Node*)* head, struct Node* node) {
struct Node* old = atomic_load(head);
do {
node->next = old;
} while (!atomic_compare_exchange_weak(head, &old, node));
}