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

前端 未结 4 767
旧巷少年郎
旧巷少年郎 2021-02-07 02:56

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

void myThread()
{
    int loop = 0;
    while(true)
    {
                


        
4条回答
  •  无人及你
    2021-02-07 04:00

    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 exiting: 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.

提交回复
热议问题