安全的乐观锁耦合
Safe Optimistic Lock Coupling

原始链接: http://databasearchitects.blogspot.com/2026/04/safe-optimistic-lock-coupling.html

随着 CPU 核心数量增加,主要的可扩展性瓶颈可能不再是算法复杂度,而是同步开销。传统锁耦合在二叉树中的表现尤其糟糕,因为每次查找都会在高度竞争的节点(尤其是根节点)上反复获取和释放共享锁,即使读者之间在语义上并不冲突。 乐观锁耦合将读者产生的写竞争移除。写入者更新数据并递增版本计数器;读者则在不加锁的情况下乐观地遍历结构,读取节点的版本和数据,然后在使用数据或移动到下一个节点之前验证版本。任何并发修改或正在进行的写入都会导致验证失败,使查找重新开始。 由于在验证之前使用数据可能引入难以察觉的竞态条件,该设计利用类型系统在编译时确保正确性。乐观访问器返回 `unvalidated` 值;这些值在经过锁守卫验证之前无法使用。即使是锁的获取和指针传递,也必须遵循这一验证链。这样既能在编译时防止不安全的读取,又能保留接近无锁的查找可扩展性以及安全的并发写入。

黑客新闻 最新 | 往期 | 评论 | 提问 | 展示 | 招聘 | 投稿 登录 安全的乐观锁耦合 (databasearchitects.blogspot.com) 5 分 由 greghn 提交 2 小时前 隐藏 | 往期 | 收藏 | 讨论 帮助 考虑申请 YC 2027 年冬季批次! 申请开放至 11 月 2 日。 指南 | 常见问题 | 列表 | API | 安全 | 法律 | 申请加入 YC | 联系我们 搜索:
相关文章

原文

As the number of CPU cores keeps growing, the scalability of concurrent data structures becomes increasingly important. A data structure that works fine on 4 cores can become a bottleneck on 32, not because of algorithmic limitations, but because of how it synchronizes access.

We illustrate that with a simple binary tree. Usually these data structures are protected by some kind of lock:

Optimistic Lock Coupling, a synchronization technique where readers do not perform any writes. The key idea here is that writers lock as usual, and increase a version number when they are done updating. Readers read the version number before access, read the elements they are interested in, and then re-check the version number. If the version number changed (or the element is currently locked), the read fails and the reader tries again. In (slightly simplified) code it looks like this:

compiler will do that in the future automatically.

Using these abstractions, our lookup code now becomes: