1. 环境
VS2019
2. 代码
- 做了一个
detach()
测试,做一个写文件的函数,使用Sleep()
函数,当主线程退出后,子线程才运行写文件函数的操作。 - 结果发现,这个函数并没有执行。
#include <iostream>
#include <thread>
#include <Windows.h>
#include <fstream>
using namespace std;
// 写入文件做测试
// 输出文件到
// 打开并覆盖文件
void writeFile() {
ofstream os("D:\\trest.txt", ios::trunc);
if (os.is_open()) {
cout << "Success to open file" << endl;
os << "Hello" << endl;
os.close();
}
}
void independentThread() {
cout << "我的线程开始运行" << endl;
Sleep(500); // 500 ms
cout << "我的线程运行完毕" << endl;
writeFile();
return;
}
void threadCaller() {
//(1)创建了线程,线程执行起点(入口)是myPrint;(2)执行线程
thread myThread(independentThread);
cout << "ID: " << myThread.get_id() << endl;
myThread.detach();
cout << "I love you" << endl;
Sleep(200);
cout << "thread is end." << endl;
}
int main() {
threadCaller();
// Sleep(2000);
return 0;
}
- 当子线程退出后,主线程才退出,这样子线程中的写文件函数才继续运行
#include <iostream>
#include <thread>
#include <Windows.h>
#include <fstream>
using namespace std;
// 写入文件做测试
// 输出文件到
// 打开并覆盖文件
void writeFile() {
ofstream os("D:\\trest.txt", ios::trunc);
if (os.is_open()) cout << "Success to open file" << endl;
os << "Hello" << endl;
os.close();
}
void independentThread() {
cout << "我的线程开始运行" << endl;
Sleep(500); // 500 ms
cout << "我的线程运行完毕" << endl;
writeFile();
return;
}
void threadCaller() {
//(1)创建了线程,线程执行起点(入口)是myPrint;(2)执行线程
thread myThread(independentThread);
cout << "ID: " << myThread.get_id() << endl;
myThread.detach();
cout << "I love you" << endl;
Sleep(200);
cout << "thread is end." << endl;
}
int main() {
threadCaller();
Sleep(2000);
return 0;
}
目前还没找到解释,只能说,主线程 (main 函数)
退出后,整个程序就退出了?暂且先留个疑问
2021-05-24
问题找到了:
在 《UNIX 网络编程》卷一 第 537 页,有这么一句话:
如果进程的main函数返回或者任何线程调用了 exit, 整个进程就终止,其中包括它的任何线程。