2016-11-01 56 views
2

我所經歷的this張貼在堆棧溢出拆離的線程中接受的答案說:資源重新分配在C++

what happens to a detached thread when main() exits is: 
It continues running (because the standard doesn't say it is stopped), and that's well-defined, as long as it touches neither (automatic|thread_local) variables of other threads nor static objects. 

雖然this後接受的答案說:

Process terminates when main() exits, and all threads are killed.

爲了查看行爲,我在g ++(Ubuntu 4.8.4-2ubuntu1〜14.04.3)4.8.4上測試了代碼,這表明一旦主線程退出其他分離線程也退出。

#include <iostream>  
#include <thread>   
#include <unistd.h> 
#include <fstream> 
using namespace std; 

void foo() 
{ 
std::cout<<"Inside foo\n"; 
int i=0; 
ofstream myfile; 


while(i<10) 
{ 
    std::cout<<"Inside while\n"; 
    myfile.open ("/home/abc/example.txt",ios::app); 
    myfile << "Writing this to a file.\n"; 
    myfile.close(); 
    i++; 
    sleep(1); 
}} 

int main() 
{ 
    std::thread first (foo);  
    first.detach(); 
    sleep(5); 
    return 0; 
} 

那麼爲什麼在這裏的堆棧溢出很多帖子表明分離線程繼續在後臺運行,即使主線程退出?在主要退出和上述哪一項是正確的情況下,分離線程繼續在後臺運行的條件是什麼?

在此先感謝。

+3

您應該閱讀對第一個鏈接的接受答案的評論。 'main()'退出時,分離線程不再存在。 –

+0

當進程結束時,與此進程相關的所有線程都將被清除。 – user743414

+0

@πάνταῥεῖ我的壞。我錯過了閱讀關於該答案的評論。感謝您指出。 – neo

回答

0

標準螺紋的範圍定義爲程序:

1.10/1:執行(也稱爲線程)的線程控制的內的程序的單個流(...)整個程序的執行包括執行其所有線程。

的標準說約分離線程:

30.3.3/1:當沒有線程對象表示該線程執行的線程被拆卸。

因此,標準中沒有任何內容暗示一個線程可以在程序中存活。

如果您想在程序結束後讓某些東西在後臺運行,您必須創建一個單獨的進程,並使用自己的資源和線程在後臺運行。