我可以在不读取值的情况下确定数据竞争的结果吗?

Can I determine the result of a data race without reading the value?

我正在努力更好地理解无锁编程:

假设我们在数据竞争中有两个线程:

// Thread 1
x = 1

// Thread 2
x = 2

有没有一种无锁的方式,第三个线程可以在无法读取 x 的情况下知道比赛的结果?

假设线程3消费一个无锁队列,代码为:

// Thread 1
x = 1
queue.push(1)

// Thread 2
x = 2
queue.push(2)

那么操作可以排序为:

x = 1
x = 2
queue.push(1)
queue.push(2)

x = 1
x = 2
queue.push(2)
queue.push(1)

因此,单独使用无锁队列不足以让线程 3 在竞争后知道 x 的值。

如果您在比赛开始前就知道 x 的值,那么使用原子读取-修改-写入操作的以下代码应该可以完成这项工作。

// Notes:
// x == 0
// x and winner are both atomic
// atomic_swap swaps the content of two variables atomically, 
// meaning, that no other thread can interfere with this operation

//thread-1:
t = 1;
atomic_swap(x, t);
if (t != 0) {
    //x was non zero, when thread-1 called the swap operation
    //--> thread-2 was faster
    winner = 1;
}    

//thread-2
t = 2;
atomic_swap(x, t);
if (t != 0) {
    //x was non zero, when thread-2 called the swap operation
    //--> thread-1 was faster
    winner = 2;
}  

//thread-3
while (winner == 0) {} 
print("Winner is " + winner);