Search code examples
c++multithreadingc++11mutexatomic

c++ Best Way to Share state between threads


The scenario is as follows: Thread A keeps executing until it receives a stop signal from thread B that keeps reading input from the console.

What is the best way to implement this? For example, I think I could implement it as a global variable that thread A keeps checking every once in a while, and thread B can change to signal "stop",

But I don't know if this is the correct way.

  • Even if it's correct, should I use "Volatile" or "Atomic<>"? Especially that thread A only reads the value of the variable and thread B only writes to the variable.

  • And what if modifying the variable from thread B right after thread A has read it doesn't matter (doesn't cause problem "thread A quitting time is somewhat relaxed(tolerated after the signal)")?

  • Is there another way for thread B to start thread A and stop it when it wants to?


Solution

  • The question will probably be closed as "too broad", however I will try to answer it (in the same "broad" fashion).

    The only imaginable answer here is: "it depends" (c)

    General advise: Try, and keep it simple (KISS principle). Start with a simple solution (like mutexes in your case), and if you ever find it unsatisfactory, replace it with another, more complex but efficient/scalable/customizable/pleasant thing (let's say atomics). If any of this will proof to be insufficient, grow complexity further (relax atomics, add lock-free stuff, build up task-based concurrency, whatever you may need) until you find the right balance.