简体   繁体   中英

how to destroy a thread explicitly created by std::thread?

I want both the threads to run in infinite loop initially, but after sometime i want to kill the first thread without waiting for it to complete, and the second should run normally. How can i implement it? When i run the below code, it gives debug error!

void f1(int i)
{
    while (1)
     {
             printf("Executng Thread  %d : %d\n", i, j);
            Sleep(10);
    }

}


int main()
{   
    std::thread t1(f1, 1);  
    std::thread t2(f1, 2);

    Sleep(100);
     t1.~thread();  
    while (1)
    {

        Sleep(10);
    }
    return 0;
}

A program executes a deterministic set of instructions following a set control flow. You cannot arbitrarily interrupt this control flow and still reason about your program behaviour.

Just like you cannot say "run my program, but not for longer than 10 seconds" without the program knowing about this and producing meaningful output, you cannot kill a thread without the thread knowing about it and producing a meaningful program state. In short, "thread cancellation requires cooperation".

Here's a simple way to make your threads cooperate: use a shared flag.

#include <atomic>
#include <chrono>
#include <thread>

std::atomic<bool> thread_1_must_end(false);

void foo(int thread_id)
{
    while (true)
    {
        if (thread_id == 1 && thread_1_must_end.load()) { break; }
        // do stuff
    }
}

int main()
{
    using std::literals::chrono_literals;

    std::thread t1(foo, 1), t2(foo, 2);
    std::this_thread::sleep_for(500ms);

    thread_1_must_end.store(true);
    t1.join();  // 1

    // ...

}

Note that this procedure is still cooperative . The join() operation (marked // 1 ) blocks until the thread function loops around and checks the flag. There are no timing guarantees for this. If the thread function ignores the flag, you cannot communicate with it. It is your responsibility to give all thread functions enough facilities to learn when it is time to end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM