android-user android-user - 3 months ago 40
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;
while(true)
{
std::this_thread::sleep_for(std::chrono::seconds(5));
++loop;
}
}

void testThread()
{
std::thread globalThread(myThread);
globalThread.detach();
}

int main(void)
{
testThread();
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

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.

Comments