Two threads using a same variable

2019-05-18 17:32发布

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

4条回答
放荡不羁爱自由
2楼-- · 2019-05-18 17:39

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.

查看更多
The star\"
3楼-- · 2019-05-18 17:42

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:

查看更多
狗以群分
4楼-- · 2019-05-18 17:47

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.

查看更多
我只想做你的唯一
5楼-- · 2019-05-18 17:49

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;
查看更多
登录 后发表回答