【发布时间】: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::threadreference,您可能会发现一些有用的东西。 -
听起来您应该为此使用
std::async。它们更简单、更安全。 -
但要小心,如果您的进程退出(通过调用
exit或从main返回),那么 所有 线程将被强制终止(正如其他人所指出的那样)这不是你崩溃的原因)。
标签: c++ multithreading c++11