如何销毁由 std::thread 显式创建的线程?

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

我希望两个线程最初都运行进入无限循环,但过了一段时间我想杀死第一个线程而不等待它完成,第二个线程应该运行正常。我该如何实施? 当我 运行 下面的代码时,它给出调试错误!

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;
}

程序按照设定的控制流执行一组确定的指令。您不能任意中断此控制流并仍然对您的程序行为进行推理。

就像你不能在程序不知道并产生有意义的输出的情况下说 "run my program, but not for longer than 10 seconds" 一样,你不能在线程不知道它并产生有意义的程序状态的情况下终止线程。简而言之,"thread cancellation requires cooperation".

这里有一个让线程协作的简单方法:使用共享标志。

#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

    // ...

}

请注意,此过程仍然合作join() 操作(标记为 // 1)阻塞,直到线程函数循环并检查标志。对此没有时间保证。如果线程函数忽略该标志,则无法与其通信。 有责任为所有线程函数提供足够的便利以了解何时结束。