Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gracefully stopping an std::thread?

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?

like image 891
shoosh Avatar asked Jun 02 '11 12:06

shoosh


2 Answers

.. 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

like image 134
Martin James Avatar answered Oct 21 '22 17:10

Martin James


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

like image 35
parapura rajkumar Avatar answered Oct 21 '22 15:10

parapura rajkumar