我可以在C ++中使用互斥锁或关键字(静态)代替volatile吗? [英] Can I use mutex or key word(static) instead of volatile in C++?
问题描述
我知道 volatile在C ++中的工作方式.但是,对于为什么我们需要波动,我仍然感到困惑.我认为的唯一原因是我们需要侦听变量是否已更改,如下代码所示:
I know how volatile works in C++. However, I'm still feeling confused about why we need volatile. Only reason I think is we need listen whether the variable changed, as the code shows below:
volatile int some_int = 100;
while(some_int==100) {
doSomething()
}
程序员需要知道单词 some_int 是否已更改,因此他使用"volatile".我可以改用关键字静态"吗?
The programmer needs know if the word some_int changed, so he uses "volatile". Could I use the key word "static" instead?
大多数情况下,如果多线程中需要同步,我认为我们应该互斥(锁定)以进行同步.不好意思的英文:)
Mostly, I think we should we mutex(lock) to synchronize if synchronization is necessary in multi-thread. Excuse my poor English:)
推荐答案
程序员需要知道some_int一词是否已更改,因此他使用"volatile".我可以改用关键字静态"
The programmer needs know if the word some_int changed, so he uses "volatile". Could I use the key word "static" instead
volatile
在C ++ 98中用于并发编程,因为当时C ++不支持多线程,因为volatile
的副作用有助于避免某些竞争情况,尽管不能保证一定会/应该管用.从C ++ 11开始,有一些工具可以正确地进行并发编程- std::mutex
和 std::atomic
,因此您应出于错误目的停止使用volatile
.使变量static
完全无关,并且不会直接影响副作用的存在.
volatile
was used in C++98 in concurrent programming because C++ did not support multi-threading as language at that time and side effects of volatile
helped to avoid some race conditions, though there were no guarantees it would/should work. Since C++11 there are tools to work with concurrent programming properly - std::mutex
and std::atomic
, so you should stop using volatile
for wrong purpose. Making variable static
is completely unrelated and would not affect existence of side effects directly.
这篇关于我可以在C ++中使用互斥锁或关键字(静态)代替volatile吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!