I have two threads: 'main' and 'worker', and one global variable bool isQuitRequested
that will be used by the main
thread to inform worker
, when it's time to quit its while loop (something like this: while(isQuitRequested == false) { ... do some stuff ... }
)
Now, I'm a bit concerned...
Do I need to use some kind of mutex protection for isQuitRequested
, considering that only one thread (main
) performs isQuitRequested = true
operation, and the other (worker
) just performs checking and nothing else?
I have read What could happen if two threads access the same bool variable at the same time?. I'ts something similar, but not the same situation...
You have not specified which language you are using and from the small code snippet that you posted it could be either C#, Java or C++. Here are some common solutions for this "pattern" for each of them:
C#:
volatile bool isQuitRequested;
Java:
volatile boolean isQuitRequested;
C++: volatile
in C++ is not nearly as useful. Go with:
std::atomic<bool> isQuitRequested;