使用“常规”变量来同步线程 [英] Use "regular" variable to synchronize threads

查看:152
本文介绍了使用“常规”变量来同步线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我只有两个线程,我想要其中一个等待另一个达到某一点,可以安全地做以下事情:

If I have only two threads, and I want one of them to wait for the other to reach a certain point, is it safe to do the following:

bool wait = true;

//Thread 1:
while(wait) ;
wait = true; //re-arm the signal

//Thread 2:
/* Preform here the code that needs to complete before Thread 1 continues */
wait = false;

基本上,如果一个线程只写入它而另一个线程只读,可能有问题吗?我假设读取或写入单个 bool 是原子的,即使不是,我不知道如何能够在这里产生差异。

Basically, if one thread only writes to it and the other only reads, can there be a problem? I assume a read or a write of a single bool is atomic, and even if not, I don't see how it can make a difference here.

推荐答案

不,它不能工作。如果你使用 std :: atomic< bool> ,它会工作。

No, it can't work. If you use std::atomic<bool> instead it will work.

C ++中的Atomics解决了三个问题。首先,在存储或读取需要多于一个总线周期的值的过程中发生线程切换的可能性;这被称为撕裂。第二,两个线程将在具有两个单独高速缓存的两个单独的处理器上运行的可能性,并且一个线程将不会看到由另一个线程做出的改变。这被称为高速缓存一致性。第三,编译器将移动代码的可能性,因为顺序似乎并不重要。

Atomics in C++ address three issues. First, the possibility that a thread switch will happen in the middle of storing or reading a value that requires more than one bus cycle; this is called "tearing". Second, the possibility that two threads will be running on two separate processors with two separate caches, and one thread won't see changes made by the other. This is called "cache coherency". Third, the possibility that the compiler will move code around because the order doesn't appear to matter.

即使 bool value可能只需要一个总线周期来读或写,它不解决其他两个问题。

Even though a bool value probably only requires one bus cycle to read or write, it doesn't address the other two issues.

没有可靠的快捷方式。使用正确的同步。

There are no reliable shortcuts. Use proper synchronization.

这篇关于使用“常规”变量来同步线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆