线程 A、B、C 各自执行工作(它们之间无需同步)。当这三个线程都完成后,线程 D 会合并它们的结果。因此,线程 D 的执行依赖于线程 A、B 和 C 的完成。
int a = 0;
int b = 0;
int c = 0;
std::atomic_int D_dependencies{ 3 };
线程A:
a = 1;
D_dependencies.fetch_sub(1, std::memory_order_release);
线程B:
b = 1;
D_dependencies.fetch_sub(1, std::memory_order_release);
线程C:
c = 1;
D_dependencies.fetch_sub(1, std::memory_order_release);
线程D:
if(D_dependencies.load(std::memory_order_acquire) == 0)
{
assert(a + b + c == 3);
}
我的理解是,RMW 操作会fetch_sub
形成一个“释放序列”,因此如果线程 D 中的加载操作从原子变量加载了 0,它应该能够观察到所有写入操作。
我理解得对吗?