一、问题
在大多数情况下,我们需要等待线程完成自己销毁,而不是强制结束,以避免资源泄漏的情况发生。
通常我们使用线程代码是用join
#include <iostream>
#include <thread>
int main()
{
bool run = true;
std::thread thread_test([&]() {
while (run);
std::cout << "Hello Thread!\n";
});
run = false;
thread_test.join();
std::cout << "Hello Main Thread!\n";
return 0;
}
当我们调用join时,主线程会等待子线程运行完成,才会运行完成:
如果在主线程中有异常情况,需要同步线程:
#include <iostream>
#include <thread>
int main()
{
bool run = true;
std::thread thread_test([&]() {
while (run);
std::cout <<