c ++ volatile多线程变量 [英] c++ volatile multithreading variables

查看:38
本文介绍了c ++ volatile多线程变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 C++ 应用程序.

I'm writing a C++ app.

我有一个类变量被多个线程写入.

I have a class variable that more than one thread is writing to.

在 C++ 中,任何可以在编译器意识到"正在更改的情况下进行修改的内容都需要标记为 volatile 对吗?因此,如果我的代码是多线程的,并且一个线程可能会写入 var 而另一个线程从中读取,我是否需要标记 var volaltile?

In C++, anything that can be modified without the compiler "realizing" that it's being changed needs to be marked volatile right? So if my code is multi threaded, and one thread may write to a var while another reads from it, do I need to mark the var volaltile?

[我没有竞争条件,因为我依赖于写入原子的整数]

[I don't have a race condition since I'm relying on writes to ints being atomic]

谢谢!

推荐答案

C++ 还没有任何多线程的规定.在实践中, volatile 并没有按照你的意思去做(它是为内存寻址硬件设计的,虽然这两个问题很相似,但它们足够不同以至于 volatile 不能做正确的事情——请注意, volatile 已用于其他在 mt 上下文中使用的语言).

C++ hasn't yet any provision for multithreading. In practice, volatile doesn't do what you mean (it has been designed for memory adressed hardware and while the two issues are similar they are different enough that volatile doesn't do the right thing -- note that volatile has been used in other language for usages in mt contexts).

因此,如果您想在一个线程中写入一个对象并在另一个线程中读取它,则必须在需要时使用您的实现所需的同步功能.对于我所知道的,volatile 在这方面没有任何作用.

So if you want to write an object in one thread and read it in another, you'll have to use synchronization features your implementation needs when it needs them. For the one I know of, volatile play no role in that.

仅供参考,下一个标准将考虑 MT,而 volatile 不会在其中发挥作用.所以这不会改变.您将只拥有需要同步的标准定义条件以及实现这些条件的标准定义方法.

FYI, the next standard will take MT into account, and volatile will play no role in that. So that won't change. You'll just have standard defined conditions in which synchronization is needed and standard defined way of achieving them.

这篇关于c ++ volatile多线程变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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