multithreading - Can I use int in multithreaded C++ safely? -
I have the following code, is there anything that will make it non-threadsof?
Class runner {public: volatile int exitFlag; // A runner built in thread () {exitFlag = 0; } // It does not matter when running in thread B void threadFunc () {// when the change is taking place here (exitFlag == 0) {// ... stuff (not using exitFlag)}} / Call it / thread with a zero sign () {exitFlag = 1; // only a bit change; }};
Let me create a runner
object and start it in another thread by threadFunc
and after some time call signalThread
I was told from the first thread that reaching the same variable in various threads (at least writing them) can be born to read the garbage value. But obviously, in the above code (only one bit has been changed) does not make any difference. Apart from this, the order of reading / writing does not matter.
unstable code
to share the variable between the atom or synchronization Does not offer a reasonable guarantee. The lack of atom is not likely to cause specific problems here, although formally it causes undefined behavior. The lack of synchronization means that it is completely possible to never see the thread change, and to carry on moving forever
in C ++ 11 or later, Use std :: atom & Lt; Integer & gt;
. Earlier versions of the language had no standard support for threads, so you have to use all the non-standard features provided by your compiler.
Comments
Post a Comment