Two threads using a same variable

2019-05-18 16:56发布

问题:

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...

回答1:

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;


回答2:

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.



回答3:

In Java you only need to mark that variable as volatile:

volatile boolean isQuitRequested;

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:

  • Stopping a specific java thread
  • java threads notify


回答4:

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.