gpt4 book ai didi

c++ - 使用加载链接/存储条件来防止 ABA 的无锁 C++11 示例?

转载 作者:搜寻专家 更新时间:2023-10-31 01:04:27 24 4
gpt4 key购买 nike

当使用比较和交换 (CAS) 技术编写无锁代码时,存在称为 ABA 问题的问题:

http://en.wikipedia.org/wiki/ABA_problem

因此,仅比较值“A”是有问题的,因为两次观察之间仍可能发生写入。我继续阅读并找到了这个解决方案:

http://en.wikipedia.org/wiki/LL/SC

In computer science, load-link and store-conditional (LL/SC) are a pair of instructions used in multithreading to achieve synchronization. Load-link returns the current value of a memory location, while a subsequent store-conditional to the same memory location will store a new value only if no updates have occurred to that location since the load-link. Together, this implements a lock-free atomic read-modify-write operation.

如何修改典型的 C++ 无锁 CAS 技术以使用上述解决方案?有人能举个小例子吗?

我不介意它是否特定于 C++11/x86、x86-64 Linux(最好没有 Win32 答案)。

最佳答案

LL/SC 是由某些架构(例如 SPARC)实现的指令,用于形成更高级别原子操作的基础。在 x86 中,您可以使用 LOCK 前缀来实现类似的目标。

要避免 x86 上带有 LOCK 的 ABA 问题,您必须提供自己的保护措施以防止干预商店。一种方法是将世代号(只是一个递增的整数)存储在与相关内存相邻的位置。每个更新程序都进行足够广泛的原子比较/交换,以包含数据和序列号。只有找到正确的数据和正确的数字,更新才会成功。同时,它更新数字以便其他线程看到更改。

您会注意到 x86 一直(?)提供了一条 CMPXCHG 指令,它的宽度是机器字的两倍(参见 CMPXCHG8B 和后来的 CMPXCGH16B ) 可用于此目的。

关于c++ - 使用加载链接/存储条件来防止 ABA 的无锁 C++11 示例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23955406/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com