在C++中,std::thread::detach()
函数用于将一个线程从其std::thread
对象中分离出来,使其成为一个后台线程或守护线程。一旦线程被分离,原始的std::thread
对象就不再与该线程相关联。当进程退出时,这个后台线程会被pcb回收,不会报错。
具体原理如下:
操作系统内核维护着进程控制块(PCB),其中包含了进程的所有状态信息和资源引用。当进程终止时,内核遍历PCB中的资源列表,释放所有分配给该进程的资源。这包括关闭所有打开的文件描述符,释放内存页,清理信号量和定时器,以及终止所有线程。
看个例子:进程自动结束后,并不会生成out.txt文件。也就是后台线程被pcb结束了。
#include <iostream>
#include <thread>
#include <fstream>
void LoopForever() {
int num = 0;
while (true) {
std::this_thread::sleep_for(std::chrono::seconds(1));
num++;
std::cout << num << std::endl;
if(num == 7){
std::string filename = "out.txt";