Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You have two different problems here. The first one is how to make a bit of data available to different parts of the code, so that the different threads can read it, while the second one is how to modify a bit of state in a thread safe way so that the threads can act on it.</p> <p>To make a bit of data available to the different threads you can use different approaches:</p> <ul> <li>If you have references to the objects that manage the threads, you can use those to manually walk the list of threads and notify each one</li> <li>You could use boost::signal at some point in the program to manage those references (i.e. create an <code>exit</code> signal, and connect all threads on construction.</li> <li>If you don't have those references, you can set the <code>exit</code> flag as a global variable and have the threads read from it</li> </ul> <p>I tend to prefer each thread to be managed by a single object, in which case I would try to move the bit of data to that manager and avoid the global. In most cases the design establishes dependencies and ownership of the resources, in which case you would not need the signals mechanism, as you can walk those dependencies.</p> <p>The second part of the problem is how to, in a thread safe way, pass the data from the main thread to the rest of the threads, and in this particular case a single bit of data that has one value during most of the program and is set to a different fixed value at one point. Whether this is a global variable or part of the state of the thread manager does not really matter:</p> <ul> <li>Mutex. Each thread locks before reading/writing ensuring that the modifications are safe</li> <li>Atomic operations. For a small enough data type, the threading library/OS offers atomic operations that will add the appropriate memory barriers to ensure the data is moved across</li> </ul> <p>Combining both what you have is either a global or a local variable that will be modified either directly (global) or through function calls triggered from the main thread, either directly or through some signals mechanism. The modification of the flag must be done either with atomic operations (introducing memory fences) or by holding a mutex. </p> <p>If the threads can be inactive (waiting on a condition variable), then you probably want to avoid the global, call the functions, lock on the mutex and inside the mutex both change the flag and use the condition variables to wake the waiting thread. The waiting thread would be responsible for checking the flag whenever it comes back from waiting in a condition.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload