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...
according to my experience on windows a global variable is usually enough if it is of one of the basic types char, short, int, long. If you want to do it the "correct way", the solution of @Tudor looks fine.
In Java you only need to mark that variable as
volatile
:Or use
AtomicBoolean
. Otherwise the change made by one thread might not be visible by other threads.However in your case there is a built-in functionality: simply call
interrupt()
on a thread and handle it, see: How to stop a thread that is running forever without any use.See also:
This should be safe with a
volatile
bool, as long as you are not using any data in the consumer (which checks the bool) thread affected by the producer thread (which sets the bool to true), AND after your consumer thread finds that the bool has been set to true, it does not attempt to reuse/reset it as a way of communicating with the producer thread (as in the example you link).This is because that case makes memory reordering a non-issue.
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#:
Java:
C++:
volatile
in C++ is not nearly as useful. Go with: