有这个简单的例子:
#include <iostream> // std::cout
#include <thread> // std::thread, std::this_thread::sleep_for
#include <chrono> // std::chrono::seconds
void new_thread(int n) {
std::this_thread::sleep_for(std::chrono::seconds(n));
std::cout << "New thread - exiting!\n";
}
int main() {
std::thread (new_thread, 5).detach();
std::cout << "Main thread - exiting!\n";
return 0;
}
是否有可能new_thread
不被主线程自动终止并完成它的工作 - 5秒后输出New thread - exiting!
?
我的意思不是主线程等待子线程时加入的情况,而是主线程分离生成的线程并终止,让新线程继续工作?
最佳答案
调用detach
在线程上意味着你不再关心线程做了什么。如果该线程在程序结束之前(当 main
返回时)没有完成执行,那么您将看不到它的效果。
但是,如果调用线程的时间足够长以使分离线程完成,那么您将看到输出。 Demo .
关于c++ - 标准线程分离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63756317/