Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread safety of read and write operations C++ [duplicate]

Reading about cancellation and pthreads, it appears to me that best practice of a thread which loops infinitely is not to cancel the thread but to create a flag that will be checked by the thread.

This situation implies that at some point, a thread might attempt to read the flag while someone is writing to the flag. Is this thread safe? How would I go about making a simultaneous get_flag() and set_flag() safe?

like image 955
wolf Avatar asked Dec 23 '13 21:12

wolf


3 Answers

Given that multiple people commented that "in practice" it is OK to read a flag and nothing can really happen, I want to first point at a nice article on benign data races. Reading this article carefully should clarify that without synchronization primitives you can get funny behavior even when sharing a bool.

The somewhat obvious approach is to use a std::atomic<bool> to safely read and write the bool from different threads. If you can't use std::atomic<T> you'll need to find a suitable replacement, possibly a mutex or a platform specific primitive.

like image 74
Dietmar Kühl Avatar answered Sep 28 '22 15:09

Dietmar Kühl


As with all inter-thread shared state, either use a thread-safe class/library for the flag, or protect it yourself in a critical section guarded by a mutex, lock, or other appropriate synchronization primitive.

like image 33
John Kugelman Avatar answered Sep 28 '22 16:09

John Kugelman


While technically it might be undefined behavior to set a variable in one thread and read it in another without protection, this is one case (of very few) where it won't matter on most modern platforms.

If the child-thread is pre-empted in the middle of checking the variable, it might miss it (or not) in the current iteration, but will catch it in the next. If the main thread is pre-empted while setting the variable, the child thread might miss it (or, again, not) and detect it in the next iteration. In short, there's normally no need to worry.

like image 25
Some programmer dude Avatar answered Sep 28 '22 16:09

Some programmer dude