android-user android-user - 1 year ago 355
C++ Question

How to terminate or stop a detached thread in c++?

I am interested in terminating/stopping/killing a detached thread in c++. How can this be done?

void myThread()
int loop = 0;

void testThread()
std::thread globalThread(myThread);

int main(void)
for(unsigned int i=0; i < 1000; i++)
cout << "i = " << i << endl;
return 0;

The reason why I'd like to "stop"/"terminate" the globalThread() is because valgrind lists that this is a "possibly lost" type of memory leak (152 bytes). What is the best way to deal with this?

Answer Source

There are no provisions to stop another thread; whether it's detached, or joinable.

The only way to stop a thread, is for the thread to return from the initial thread function.

In this particular case, I would suggest the following changes:

  1. Do not detach the thread. Instantiate it in main().
  2. Add a bool value, and a std::mutex, the bool gets initialized to false
  3. Each time through the thread's inner loop, lock the mutex using a std::unique_lock, take the bool's value, then unlock the mutex. After unlocking the mutex, if the bool was true, break out of the loop, and return.
  4. In main(), before existing: lock the mutex, set the bool flag to true, unlock the mutex, then join the thread

This is not perfect, since it will take up to five seconds for the second thread to check the bool flag, and return. But, this would be the first tep.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download