c++ std::thread join/detach用法
detach
分离线程,将对象表示的线程与调用线程分离,允许它们彼此独立执行。
两个线程在没有阻塞或同步的情况下继续运行。注意,当任何一个结束执行时,它的资源都会被释放。让被创建的线程为后台线程,否则主线程退出时,如果子线程没有退出则异常。
#include <iostream>
#include <thread>
using namespace std;
void func1() {
cout << "func1" << endl;
}
void func2() {
cout << "func2" << endl;
}
int main() {
thread t1(func1);
thread t2(func2);
return 0;
}
如果直接执行上面的程序,会报错:
void func1() {
std::cout << "func1" << std::endl;
}
void func2() {
std::cout << "func2" << std::endl;
}
分离后,则正常:
std::thread t1(func1);
t1.detach();
std::thread t2(func2);
t2.detach();
join
在上面的情况中,一般使用join来解决:
#include <iostream>
#include <thread>
using namespace std;
void func1() {
cout << "func1" << endl;
}
void func2() {
cout << "func2" << endl;
}
int main() {
thread t1(func1);
t1.join();
thread t2(func2);
t2.join();
return 0;
}
但是还是有可能还是会出现问题,异常情况下可能会存在资源泄露的问题,利用c++的rall机制,可以在析构函数中join,自定义线程类:
#include <iostream>
#include <thread>
using namespace std;
class my_thread {
public:
my_thread(std::thread& t) :thread_(t) {}
~my_thread() {
if (thread_.joinable()) {
std::cout << "thread id: " << std::this_thread::get_id() << std::endl;
thread_.join();
}
}
my_thread(const my_thread& t) = delete;
my_thread& operator = (const my_thread&) = delete;
private:
std::thread& thread_;
};
void func1() {
cout << "func1" << endl;
}
void func2() {
cout << "func2" << endl;
}
int main() {
thread t1(func1);
my_thread my(t1);
thread t2(func2);
my_thread my2(t2);
return 0;
}
阅读 485
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。