以下程序在偶尔打印“坏”输出时给了我意想不到的行为。这两个线程应该使用两个 std::atomic 变量“s_lock1”和“s_lock2”进行同步。在 func2 中,为了将 's_var' 变量设置为 1,它必须在 's_lock2' 中原子地存储一个非零值,并且另一个线程 (func1) 必须尚未更新 's_lock1' 变量。然而,在 func1 中,它以某种方式打印了意外的“坏”输出。s_lock2.load() 语句似乎返回 false。这个代码片段有什么问题吗?这是与内存排序有关的问题吗?
我在安装了 Centos 7 的 8 核 Linux 服务器上运行它。任何帮助是极大的赞赏。
#include <iostream>
#include <thread>
#include <atomic>
#include <unistd.h>
std::atomic_uint s_lock1 = 0;
std::atomic_uint s_lock2 = 0;
std::atomic_uint s_var = 0;
static void func1()
{
while (true) {
s_lock1.store(1, std::memory_order_release);
if (s_lock2.load(std::memory_order_acquire) != 0) {
s_lock1.store(0, std::memory_order_release);
continue;
}
if (s_var.load(std::memory_order_acquire) > 0) {
printf("bad\n");
}
usleep(1000);
s_lock1.store(0, std::memory_order_release);
}
}
static void func2()
{ …Run Code Online (Sandbox Code Playgroud)