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

前端 未结 4 766
旧巷少年郎
旧巷少年郎 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 03:57

    You could drop below the C++ Standard and use OS-specific functions, such as sending your own process a signal while setting the signal mask so it's delivered only to the detached thread - a handler can set a flag that's polled from your thread. If your main routine waits longer than the poll period plus a bit you can guess it should have terminated ;-P. The same general idea can be used with any other signalling mechanism, such as an atomic terminate-asap flag variable.

    Alternatively, and only as a last resort, there's pthread_cancel and similar. Note that async cancellation like this is a famously dangerous thing to do in general - you should be careful that the thread you terminate can't be in any code with locked/taken resources or you may have deadlocks, leaks, and/or undefined behaviour. For example, your code calls std::this_thread::sleep_for(std::chrono::seconds(5)); - what if that asks the OS for a callback when the interval expires, but the function to continue to afterwards uses the terminated thread's stack? An example where it can be safe is if the thread's doing some simple number crunching in a loop within your app.

    Otherwise Sam's answer documents an alternative if you avoid detaching the thread in the first place....

提交回复
热议问题