笔记 C++ thread::detach() 后 main() 退出后,派生线程不再运行

本文探讨了在VS2019环境中,使用detach方法进行线程分离时遇到的问题。当主线程结束时,子线程未能正确执行写文件操作,通过调整主线程等待时间解决了该问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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, 整个进程就终止,其中包括它的任何线程。

评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值