Solved

How to gracefully close the c++ 11 thread?

Posted on 2016-09-19
3
66 Views
Last Modified: 2016-09-23
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
0
Comment
Question by:EeEd EeEd
3 Comments
 
LVL 61

Expert Comment

by:gheist
ID: 41806274
When thread function exits thread finishes.
0
 
LVL 32

Accepted Solution

by:
sarabande earned 250 total points
ID: 41806490
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
 
LVL 27

Assisted Solution

by:tliotta
tliotta earned 250 total points
ID: 41807786
"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

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

If you have a server on collocation with the super-fast CPU, that doesn't mean that you get it running at full power. Here is a preamble. When doing inventory of Linux servers, that I'm administering, I've found that some of them are running on l…
Setting up Secure Ubuntu server on VMware 1.      Insert the Ubuntu Server distribution CD or attach the ISO of the CD which is in the “Datastore”. Note that it is important to install the x64 edition on servers, not the X86 editions. 2.      Power on th…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now