首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我可以在不读取值的情况下确定数据竞争的结果吗?

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

Stack Overflow用户
提问于 2018-07-23 15:21:40
回答 1查看 76关注 0票数 4

我试图更好地理解无锁编程:

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

代码语言:javascript
运行
复制
// Thread 1
x = 1

// Thread 2
x = 2

有无锁的方式吗?第三个线程可以在不读取x?的情况下知道竞赛的结果。

假设线程3使用一个无锁队列,代码是:

代码语言:javascript
运行
复制
// Thread 1
x = 1
queue.push(1)

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

然后,这些操作可以命令如下:

代码语言:javascript
运行
复制
x = 1
x = 2
queue.push(1)
queue.push(2)

代码语言:javascript
运行
复制
x = 1
x = 2
queue.push(2)
queue.push(1)

因此,仅有一个没有锁的队列并不足以让线程3在比赛后知道x的值。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-23 16:53:06

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

代码语言:javascript
运行
复制
// 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);
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51482272

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档