I have a worker std::thread
and I want its main loop to check if some other thread tells it to stop looping and exit.
What is a good cross platform way to do this? Does boost provide some event object for it?
Is using just a bool
considered thread-safe?
.. well it depends. What is the thread doing? Does it block on anything, I/O, sleep
, or some other API?
If it's just CPU-looping all the time and it does not matter about exactly when it stops and it stops and exits, then just use a boolean. There's no point, in this case, in locking up a 'stopAndExit' boolean.
If the work thread does not read it as true on one loop when perhaps it should, because of some lack of atomicity, it will get it next time round. Why perform locks/API calls when you don't have to? A kernel level call from user to acquire/release a synchronisation object will take ages compared with a simple 'if (stop) exit;', wasting time on each loop that could have been used for calculation, or whatever you do in your CPU-bound thread.
It is cross-platform
Regards, Martin
What you could have is a std::mutex that is shared between primary and your worker thread.
Your worker thread can acquire std::mutex::try_lock before commencing any work and release it intermittently . The main thread can lock this mutex when it wants your worker thread to shut down. Your worker thread can detect this using try_lock and exit
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With