在 Linux 内核多核调度中,读多写少的高性能链表通常使用 RCU(Read-Copy Update) 替代粗粒度自旋锁。读者无需加锁获取指针,写者则通过拷贝旧对象进行修改,并等待“宽限期(Grace Period)”结束再释放老旧内存。
一、RCU 核心 API 读写规范
c
// 读者端:快速无锁安全访问
rcu_read_lock();
struct node *p = rcu_dereference(head);
if (p) {
access_payload(p->data);
}
rcu_read_unlock();
// 写者端:替换指针后等待宽限期回收
void update_node(struct node *new_node) {
struct node *old_node = head;
rcu_assign_pointer(head, new_node);
synchronize_rcu(); // 阻塞等待所有旧读者退出读临界区
kfree(old_node);
}