我试图更好地理解无锁编程:
假设数据竞争中有两个线程:
// 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的值。
发布于 2018-07-23 16:53:06
如果您在竞赛开始前就知道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);
https://stackoverflow.com/questions/51482272
复制相似问题