std :: thread从函数启动而不等待线程完成

时间:2018-05-03 18:46:51

标签: c++ multithreading c++11

如果我评论t.join()

,我很难看到这个小程序会中止
void my_thread()
{
    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::cout << "thread completed\n";
}

void main()
{
    std::cout << "starting thread...\n";
    std::thread t(my_thread);

    t.join();  //<=== my program aborts when I comment this line

    std::cout << "press a key to quit..." << std::endl;
    std::getchar();
}

我想编写一个不等待线程完成的函数。

我该如何解决这个工作示例?

#include <iostream>
#include <thread>
#include <chrono>

void my_thread()
{
    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::cout << "thread completed\n";
}

void send_message()
{
    std::cout << "starting thread...\n";

    std::thread t(my_thread);

    t.join();  //<=== the function aborts when I comment this line
}

void main()
{
    send_message();
    std::cout << "press a key to quit..." << std::endl;
    std::getchar();
}

1 个答案:

答案 0 :(得分:3)

如果在调用析构函数时你的线程是joinable,那么它将调用std::terminate。您需要分离或加入。

Reference