问题
I have a single public variable in a class
bool toSwitch = false;
Func_Thread1()
{
if(toSwitch)
{
.....
....
toSwitch = false;
}
}
and
Func_Thread2()
{
toSwitch = 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.
Does the toSwitch
needs synchronization as it can read and modified by different threads concurrently ..?
Update 2:
What happens in this environment...?
Func_Thread1()
{
if(toSwitch)
{
.....
....
}
else
{
...
}
}
and
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 .?
回答1:
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:
- For the compiler to not reorder your reads and writes around access to the shared variable.
- For other threads to see updates to this variable in consistent (atomic) and timely (flush the store buffer to the cache) fashion.
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>
.
回答2:
You need synchronization. Unsynchronized access to a shared memory location (toSwitch
) from more than one thread where at least one access is a write (toSwitch = true;
) constitutes a data race, which makes the behaviour of your program undefined.
来源:https://stackoverflow.com/questions/32819166/c-concurrent-modification-and-read-of-a-single-global-variable