How do I terminate a thread in C++11?

后端 未结 5 2302
长发绾君心
长发绾君心 2020-11-22 09:42

I don\'t need to terminate the thread correctly, or make it respond to a \"terminate\" command. I am interested in terminating the thread forcefully using pure C++11.

5条回答
  •  悲&欢浪女
    2020-11-22 10:45

    I guess the thread that needs to be killed is either in any kind of waiting mode, or doing some heavy job. I would suggest using a "naive" way.

    Define some global boolean:

    std::atomic_bool stop_thread_1 = false;
    

    Put the following code (or similar) in several key points, in a way that it will cause all functions in the call stack to return until the thread naturally ends:

    if (stop_thread_1)
        return;
    

    Then to stop the thread from another (main) thread:

    stop_thread_1 = true;
    thread1.join ();
    stop_thread_1 = false; //(for next time. this can be when starting the thread instead)
    

提交回复
热议问题