c++ - 可能同时从不同的线程读取全局变量是否危险?

标签 c++ boost-thread

所以我正在编写这个简洁的小程序来自学线程,我正在使用 boost::thread 和 C++ 来这样做。

我需要主线程与工作线程通信,为此我一直在使用全局变量。它按预期工作,但我不禁感到有些不安。

如果工作线程试图在主线程读取值的同时写入全局变量会怎样。这是不好的、危险的,还是希望在幕后考虑到这一点?

最佳答案

§1.10 [intro.multithread](引用 N4140):

6 Two expression evaluations conflict if one of them modifies a memory location (1.7) and the other one accesses or modifies the same memory location.

23 Two actions are potentially concurrent if

  • they are performed by different threads, or
  • they are unsequenced, and at least one is performed by a signal handler.

The execution of a program contains a data race if it contains two potentially concurrent conflicting actions, at least one of which is not atomic, and neither happens before the other, except for the special case for signal handlers described below. Any such data race results in undefined behavior.

纯粹并发读取不会冲突,因此是安全的。

如果至少一个线程写入内存位置,而另一个线程从该位置读取,则它们会发生冲突并可能并发。结果是数据竞争,因此是未定义的行为,除非使用适当的同步,通过对所有读取和写入使用原子操作,或者通过使用同步原语在读取之间建立先于关系和写。

关于c++ - 可能同时从不同的线程读取全局变量是否危险?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28591370/

相关文章:

c++ - 连接器/C++ MySQL 错误代码 : 2014 , SQLState : HY000 and Commands out of sync error why?

c++ - 复制和赋值

c++ - 如何在静态函数中使用成员函数数组?

c++ - 执行简单的 boost 线程程序时出错

c++ - 如何在C++中为每个对象实现计时器?

C++ 无法推导出模板参数

c++ - boost::thread::join() 崩溃试图引用销毁的 thread_info

c++ - 在 clang++ 中使用 boost/thread header 时遇到问题 (Windows)

c++ - C++中的二维动态内存分配数组

c++ - boost::thread - 简单示例不起作用 (C++)