2017-01-23 33 views
0

我知道很多人问这个问题,但我不是“很多人”,我需要一个不同的,更好的解释来理解。线程上的“detach()”是什么? CPP

成员函数“detach()”到底是什么? 我试着运行一个代码示例:

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

void independentThread() 
{ 
    std::cout << "Starting concurrent thread.\n"; 
    std::this_thread::sleep_for(std::chrono::seconds(200)); 
    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(5)); 
} 

并在5秒内的所有程序关闭。 我认为程序会在“main”关闭后的另一个195秒后打开,因为“detach”的所有概念都是与main无关的,所以以独立的方式,它应该仍然运行直到所有分离的游戏都终止... 我阅读文档并来到这里。 更好的解释 - 请! :)

+0

通过使用['std :: async'](http://en.cppreference.com/w/cpp/thread/async)使您的生活更轻松。 –

回答

0

分离线程是一个线程,你不能等待完成。析构函数会检查线程是分离的还是加入的,如果两者都不存在,则会中止一个程序(调用std::terminate)。

main()终止后,程序无条件终止,不等待任何线程,分离或其他。

+0

我不明白你......那么为什么它需要?!例如,在python中,没有任何“分离”,程序本身不会中止!为什么我必须使用它?它是什么让我恶心? –

+0

@fdwfgwdfwdfv,可能不会以任何方式帮助你。你可能想要坚持使用Python。 – SergeyA

+0

只是请更好地解释它,所以我可以理解..我没有问那个男人更多:\ –