Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it ok to read a shared boolean flag without locking it when another thread may set it (at most once)?

I would like my thread to shut down more gracefully so I am trying to implement a simple signalling mechanism. I don't think I want a fully event-driven thread so I have a worker with a method to graceully stop it using a critical section Monitor (equivalent to a C# lock I believe):

DrawingThread.h

class DrawingThread {     bool stopRequested;     Runtime::Monitor CSMonitor;     CPInfo *pPInfo;     //More.. } 

DrawingThread.cpp

void DrawingThread::Run() {     if (!stopRequested)         //Time consuming call#1     if (!stopRequested) {         CSMonitor.Enter();         pPInfo = new CPInfo(/**/);         //Not time consuming but pPInfo must either be null or constructed.          CSMonitor.Exit();     }     if (!stopRequested) {         pPInfo->foobar(/**/);//Time consuming and can be signalled     }     if (!stopRequested) {         //One more optional but time consuming call.     } }   void DrawingThread::RequestStop() {     CSMonitor.Enter();     stopRequested = true;     if (pPInfo) pPInfo->RequestStop();     CSMonitor.Exit(); } 

I understand (at least in Windows) Monitor/locks are the least expensive thread synchronization primitive but I am keen to avoid overuse. Should I be wrapping each read of this boolean flag? It is initialized to false and only set once to true when stop is requested (if it is requested before the task completes).

My tutors advised to protect even bool's because read/writing may not be atomic. I think this one shot flag is the exception that proves the rule?

like image 643
John Avatar asked Feb 08 '12 20:02

John


People also ask

Is bool thread safe?

The Interlocked class provides a lock-free, non-blocking approach to thread-safety. Not only does it isolate the complexity, but it also provides better performance by eliminating the overhead incurred by locks. The following code shows how to use the Interlocked class to make the bool property thread-safe.


1 Answers

It is never OK to read something possibly modified in a different thread without synchronization. What level of synchronization is needed depends on what you are actually reading. For primitive types, you should have a look at atomic reads, e.g. in the form of std::atomic<bool>.

The reason synchronization is always needed is that the processors will have the data possibly shared in a cache line. It has no reason to update this value to a value possibly changed in a different thread if there is no synchronization. Worse, yet, if there is no synchronization it may write the wrong value if something stored close to the value is changed and synchronized.

like image 180
Dietmar Kühl Avatar answered Sep 21 '22 21:09

Dietmar Kühl