标准线程分离
Std thread detach
有这个简单的例子:
#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!
?
我不是说 join
主线程等待子线程的情况,而是主线程分离生成的线程并终止让新线程执行它的工作?
detach
将您的线程与主线程分开。你想使用 join()
Separates the thread of execution from the thread object, allowing
execution to continue independently. Any allocated resources will be
freed once the thread exits.
After calling detach *this no longer owns any thread.
来自ref
在一个线程上调用detach
意味着你不再关心线程做了什么。如果该线程在程序结束之前没有完成执行(当 main
returns),那么您将看不到它的效果。
但是,如果调用线程的运行时间足以让分离的线程完成,那么您将看到输出。 Demo.
[basic.start.main]/5 A return statement in main
has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling std::exit
with the return value as the argument. If control flows off the end of the compound-statement of main
, the effect is equivalent to a return
with operand 0.
[support.start.term]/9
[[noreturn]] void exit(int status);
Effects:
...
- Finally, control is returned to the host environment.
您似乎期望当 main
returns 时,程序等待所有线程完成 - 实际上,隐式连接所有分离的线程。事实并非如此 - 相反,程序终止,操作系统清理分配给进程(包括任何线程)的资源。
有这个简单的例子:
#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!
?
我不是说 join
主线程等待子线程的情况,而是主线程分离生成的线程并终止让新线程执行它的工作?
detach
将您的线程与主线程分开。你想使用 join()
Separates the thread of execution from the thread object, allowing execution to continue independently. Any allocated resources will be freed once the thread exits.
After calling detach *this no longer owns any thread.
来自ref
在一个线程上调用detach
意味着你不再关心线程做了什么。如果该线程在程序结束之前没有完成执行(当 main
returns),那么您将看不到它的效果。
但是,如果调用线程的运行时间足以让分离的线程完成,那么您将看到输出。 Demo.
[basic.start.main]/5 A return statement in
main
has the effect of leaving the main function (destroying any objects with automatic storage duration) and callingstd::exit
with the return value as the argument. If control flows off the end of the compound-statement ofmain
, the effect is equivalent to areturn
with operand 0.
[support.start.term]/9
[[noreturn]] void exit(int status);
Effects:
...
- Finally, control is returned to the host environment.
您似乎期望当 main
returns 时,程序等待所有线程完成 - 实际上,隐式连接所有分离的线程。事实并非如此 - 相反,程序终止,操作系统清理分配给进程(包括任何线程)的资源。