【问题标题】:std::thread started from a function without waiting the thread to complete [duplicate]std::thread 从一个函数开始而不等待线程完成[重复]
【发布时间】:2018-05-03 18:46:50
【问题描述】:

如果我评论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();
}

【问题讨论】:

  • 如果您查看a good std::thread reference,您可能会发现一些有用的东西。
  • 听起来您应该为此使用std::async。它们更简单、更安全。
  • 但要小心,如果您的进程退出(通过调用exit 或从main 返回),那么 所有 线程将被强制终止(正如其他人所指出的那样)这不是你崩溃的原因)。

标签: c++ multithreading c++11


【解决方案1】:

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

Reference.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多