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;
}
那麼爲什麼在這裏的堆棧溢出很多帖子表明分離線程繼續在後臺運行,即使主線程退出?在主要退出和上述哪一項是正確的情況下,分離線程繼續在後臺運行的條件是什麼?
在此先感謝。
您應該閱讀對第一個鏈接的接受答案的評論。 'main()'退出時,分離線程不再存在。 –
當進程結束時,與此進程相關的所有線程都將被清除。 – user743414
@πάνταῥεῖ我的壞。我錯過了閱讀關於該答案的評論。感謝您指出。 – neo