Two threads using a same variable

给你一囗甜甜゛ 提交于 2019-12-06 04:22:51

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;

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.

Tomasz Nurkiewicz

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:

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!