I am interested in terminating/stopping/killing a detached thread in c++. How can this be done?
void myThread()
{
int loop = 0;
while(true)
{
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:
std::mutex
, the bool gets initialized to false
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.true
, unlock the mutex, then join the threadThis 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.