我可以在C ++中使用互斥锁或关键字(静态)代替volatile吗? [英] Can I use mutex or key word(static) instead of volatile in C++?

查看:83
本文介绍了我可以在C ++中使用互斥锁或关键字(静态)代替volatile吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 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屋!

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