C++ std::thread 类 detach 函数详解 - 如何分离线程
"std::thread" 类是 C++11 标准库中用于线程操作的类,它提供了创建、管理和操作线程的功能。其中,"detach" 函数是 "std::thread" 类中的一个成员函数,用于将线程从当前 "std::thread" 对象中分离出来。\n\n"detach" 函数的函数原型如下:\n\ncpp\nvoid detach();\n\n\n"detach" 函数没有参数,也没有返回值。它的作用是将当前 "std::thread" 对象所代表的线程从当前进程中分离出来,并允许线程在后台继续运行,不再与 "std::thread" 对象关联。\n\n当调用 "detach" 函数后,"std::thread" 对象会释放与线程相关的资源,但不会等待线程执行完毕。此时,如果 "std::thread" 对象销毁,或者 "std::thread" 对象的析构函数被调用,而线程仍在执行,则程序会终止。因此,在调用 "detach" 函数后,需要确保线程能够正常执行完毕,否则可能会导致资源泄漏或程序崩溃。\n\n使用 "detach" 函数的示例如下:\n\ncpp\n#include <iostream>\n#include <thread>\n\nvoid threadFunc() {\n // 线程执行的代码\n std::cout << \"Thread is running.\" << std::endl;\n std::this_thread::sleep_for(std::chrono::seconds(2));\n std::cout << \"Thread is done.\" << std::endl;\n}\n\nint main() {\n std::thread t(threadFunc);\n t.detach();\n\n // 主线程的代码\n std::cout << \"Main thread is running.\" << std::endl;\n std::this_thread::sleep_for(std::chrono::seconds(1));\n std::cout << \"Main thread is done.\" << std::endl;\n\n return 0;\n}\n\n\n在上述示例中,"detach" 函数被调用后,子线程会在后台继续执行,不再与 "std::thread" 对象关联。主线程会继续执行自己的代码,不会等待子线程执行完毕。运行程序后,可以看到主线程和子线程同时执行,且主线程先于子线程结束。
原文地址: https://www.cveoy.top/t/topic/pRaX 著作权归作者所有。请勿转载和采集!