Can you please tell me if the following code is thread safe?
I think I am encountering a race condition, because Task2 does not get executed even though I have set the value of params.b to be true from the GUI.
struct params {
params() {}
~params() {}
atomic_bool a;
atomic_bool b;
};
struct driver {
driver() {}
~driver() {}
params myParams;
void tFun() {
while (1) {
if (myParams.a) { /* DoTask1 */ }
if (myParams.b) { /* DoTask2 */ }
}
}
void DoSome() {
std::thread t(&driver::tFun, this);
t.detach();
while (1) {
myParams.a = fromGui.val;
myParams.b = fromGui.val;
}
}
};
int main() {
driver myDriver;
myDriver.DoSome();
return 0;
}
Please execuse my 'fromGui.val' usage, it is supposed to indicate that this value will be loaded from the GUI.
The situation I can see is that there is a race between fTun() function and DoSome():
For example:
1. DoSome() sets a,b true
2. tFun() executes in while loop, as a is true, it starts DoTask1
2. DoSome() sets a,b to false
3. tFun() finishes DoTask1 and come to check myParams.b which is false;
DoTask2 is ignored!!
4. loop continues to step 1
If you always set a,b to true, then there is no race to compare with, tasks DoTask1 & DoTask2 should both be executed
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With