从潜在的同时从不同的线程读取全局变量是危险的吗? [英] Is it dangerous to read global variables from separate threads at potentially the same time?

查看:319
本文介绍了从潜在的同时从不同的线程读取全局变量是危险的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我写这个整洁的小程序来教自己的线程,我使用boost ::线程和C ++这样做。



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



如果工作线程在主线程读取值的同时尝试写入全局变量,该怎么办?

解决方案

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


6如果其中一个修改
内存位置, 1.7),另一个访问或修改相同的
内存位置。



23两个动作可能并发 >


  • 它们是由不同的线程执行的,或

  • 它们不被排序,至少一个由信号处理程序。



程序的执行包含数据竞争如果它包含两个
潜在并发的冲突动作,其中至少一个是
不是原子的,并且不会在另一个之前发生,除了下面描述的用于信号处理器的
特殊情况。任何此类数据竞争
会导致未定义的行为。


因此是安全的。



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


So I'm writing this neat little program to teach myself threading, I'm using boost::thread and C++ to do so.

I need the main thread to communicate with the worker thread, and to do so I have been using global variables. It is working as expected, but I can't help but feel a bit uneasy.

What if the the worker thread tries write to a global variable at the same time as the main thread is reading the value. Is this bad, dangerous, or hopefully taken into account behind the scenes??

解决方案

§1.10 [intro.multithread] (quoting 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.

Purely concurrent reads do not conflict, and so is safe.

If at least one of the threads write to a memory location, and another reads from that location, then they conflict and are potentially concurrent. The result is a data race, and hence undefined behavior, unless appropriate synchronization is used, either by using atomic operations for all reads and writes, or by using synchronization primitives to establish a happens before relationship between the read and the write.

这篇关于从潜在的同时从不同的线程读取全局变量是危险的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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