【发布时间】:2019-05-02 18:31:23
【问题描述】:
需要帮助为什么以下代码的工作方式不同。 在此代码中,主退出后线程不打印任何内容:
#include <iostream>
#include <chrono>
#include <thread>
using namespace std;
void Run()
{
cout<<"=== "<< "start_point" <<" ==="<<endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
cout<<"=== "<< "start_point" <<" ==="<<endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
cout<<"=== "<< "start_point" <<" ==="<<endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
cout<<"=== "<< "start_point" <<" ==="<<endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
cout<<"=== "<< "start_point" <<" ==="<<endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
cout<<"=== "<< "start_point" <<" ==="<<endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
cout<<"=== "<< "start_point" <<" ==="<<endl;
}
int main()
{
std::thread th(Run);
th.detach();
std::this_thread::sleep_for(std::chrono::seconds(2));
cout<<"==== Ending main ==="<<std::endl;
}
但是这里在线程退出后会打印正确的消息:
void independentThread()
{
std::cout << "Starting concurrent thread.\n";
std::this_thread::sleep_for(std::chrono::seconds(2));
std::cout << "Exiting concurrent thread.\n";
}
void threadCaller()
{
std::cout << "Starting thread caller.\n";
std::thread t(independentThread);
t.detach();
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Exiting thread caller.\n";
}
int main()
{
threadCaller();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
应该是非常小的东西,我想念它。 编译器信息: g++/Mac/c++11
试图在谷歌上搜索,但没有运气。
编辑-1: 第一个程序的结果:
=== start_point ===
=== start_point ===
==== Ending main ===
第二个项目的结果:
Starting thread caller.
Starting concurrent thread.
Exiting thread caller.
Exiting concurrent thread.
【问题讨论】:
标签: multithreading c++11 detach