问题描述
我在一个类中只有一个公共变量
I have a single public variable in a class
bool toSwitch = false;
bool toSwitch = false;
Func_Thread1()
{
if(toSwitch)
{
.....
....
toSwitch = false;
}
}
和
Func_Thread2()
{
toSwitch = true;
}
Func_Thread1
将被频繁调用(2秒一次),在一定的间隔内,Func_Thread2
将被调用(1分钟一次),并将全局变量更改为true.因此,在下一个Func_Thread1
调用中,if条件将变为true.
The Func_Thread1
will get called frequently(2 seconds once) and during certain interval Func_Thread2
will get called(1 minute once) and change the global variable to true. So at the next Func_Thread1
call the if condition will become true.
toSwitch
是否需要同步,因为它可以同时由不同的线程读取和修改..?
Does the toSwitch
needs synchronization as it can read and modified by different threads concurrently ..?
更新2:
在这种环境下会发生什么...?
What happens in this environment...?
Func_Thread1()
{
if(toSwitch)
{
.....
....
}
else
{
...
}
}
和
Func_Thread2()
{
if(toSwitch)
{
toSwitch = false;
}
else
{
toSwitch = true;
}
}
在这里需要同步吗,其中一个线程修改而另一个线程读取该全局变量的值.
Does sync needs here , where one thread modifies and other thread reads the value of that global variable .?
推荐答案
如果一个对象被多个线程访问,并且至少一个线程是写程序,则它是数据竞争.
If an object is accessed by more than one thread and at least one thread is a writer that is a data race.
您出于以下原因需要同步:
You need synchronization for the following reasons:
- 为了使编译器不对访问共享变量的访问进行重新排序.
- 让其他线程以一致的方式(原子)及时地(将存储缓冲区刷新到缓存)查看此变量的更新.
您的硬件可能能够以原子方式存储bool
,但是,出于上述其余原因,您可能希望使用std::atomic<bool>
.
Your hardware is likely to be able to store a bool
in atomic fashion, however, for the remaining reasons above you may like to use std::atomic<bool>
.
这篇关于C ++并发修改和读取单个全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!