shoosh
shoosh

Reputation: 78914

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?

Upvotes: 9

Views: 13824

Answers (4)

Martin James
Martin James

Reputation: 24847

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

Upvotes: 6

Daniel
Daniel

Reputation: 147

As you mentioned boost, there is boost::thread you can use.

In your case, after starting a thread, you could interrupt it by using the interrupt() method. The receiver thread can check for interrupt requests with the boost::this_thread::interruption_point() method. This will cause the thread to exit if there is an interruption request, otherwise, it will ignore it.

You can check the documentation here: Boost Thread Documentation

Upvotes: 0

holtavolt
holtavolt

Reputation: 4458

std::mutex and it's relatives are the core mechanisms. std::lock_guard and unique_lock build on this, and std::condition_variable are good for this purpose.

Upvotes: 0

parapura rajkumar
parapura rajkumar

Reputation: 24403

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

Upvotes: 2

Related Questions