How to gracefully close the c++ 11 thread?

Hi,

  Created C++ 11 thread by using std::thread. Running in parallel to main program/thread. Now, in some situation, I want to kill or terminate that thread gracefully.

What is the best way to kill child/other threads.

Ed
EeEd EeEdAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
sarabandeConnect With a Mentor Commented:
When thread function exits thread finishes.

... gracefully.

therefore, you always should add a way how to return from thread function (and break the - infinite - loop) on request of the main thread. the simplest to do so, is to provide a shared bool variable (stop flag) which was checked by the thread periodically. to stop the thread the main thread would set the bool  and either wait until the thread has recognized the stop flag and exited, or if the results of the thread are no longer needed, simply goes on. the thread may reset the shared stop flag before exit.

Sara
1
 
gheistCommented:
When thread function exits thread finishes.
0
 
tliottaConnect With a Mentor Commented:
"Best" way is probably to send some signal that the thread can react to to have it end itself. But that really isn't "kill" a thread. When you "kill" any process, it's almost not "graceful" by definition.
0
All Courses

From novice to tech pro — start learning today.