🐭 线程 joinable
在 C++ 中一个 std::thread 线程对象要么是 joinable 的,要么是 unjoinable 的,std::thread 大多数时候是 joinable (可连接) 的,在下面几种情况下,线程是 unjoinable (不可连接) 的:
- 没有指定执行对象的默认线程对象
- 线程对象已经被移动到别的线程对象
- 线程对象已经执行 join 操作
- 线程对象已经 detach 操作
代码示例 :
#include <future>#include <iostream>#include <thread>int sum(int a, int b) { return a + b; }int main() {// std::thread joinablestd::cout << std::boolalpha;// case 1: default thread object, no thread function is specified{std::thread t;std::cout << t.joinable() << std::endl; // false}// case 2: the thread object is moved away{std::thread t(sum, 1, 2);std::cout << t.joinable() << std::endl; // truestd::thread t1(std::move(t));std::cout << t.joinable() << std::endl; // falset1.join();}// case 3: the thread object is already joined{std::thread t(sum, 1, 2);std::cout << t.joinable() << std::endl; // truet.join();std::cout << t.joinable() << std::endl; // false}// case 4: the thread object have been detached{std::thread t(sum, 1, 2);std::cout << t.joinable() << std::endl; // truet.detach();std::cout << t.joinable() << std::endl; // false}return 0;}
🐂 std::thread 的销毁机制
在 C++ 中 std::thread 线程对象也有其生命周期,当线程对象离开其作用域的时候会被析构函数自动销毁,线程销毁是件比较麻烦的事情,因为涉及到底下对应的操作系统软件线程的销毁。
C++ 标准规定,不允许析构一个 joinable 的线程对象,否则会调用 std::terminate 来结束整个程序,这个一般是不可接受的。因此,我们必须要保证 std::thread 对象在析构之前必须是 unjoinable 的。
🐯 std::thread 与 RAII
要保证 std::thread 对象在析构之前必须是 unjoinable 的,这个与保证资源一定会被释放类似,我们可以使用 RAII 魔法来处理这种线程 unjoinable 的问题。
代码示例 :
#include <iostream>#include <thread>class ThreadRAII {public:enum class action { join, detach };ThreadRAII(std::thread &&thd, action act) : thd_(std::move(thd)), act_(act) {}~ThreadRAII() {if (thd_.joinable()) {if (act_ == action::join) {thd_.join();} else {thd_.detach();}}}ThreadRAII(ThreadRAII &&) = default;ThreadRAII &operator=(ThreadRAII &&) = default;std::thread &get() { return thd_; }private:std::thread thd_;action act_;};int sum(int a, int b) { return a + b; }int main() {// need to call join{std::thread t(sum, 1, 2);std::cout << t.get_id() << std::endl; // 0x70000af43000t.join(); // comment out this line will crash the whole program}// no need to call join{ThreadRAII t(std::thread(sum, 2, 2), ThreadRAII::action::join);std::cout << t.get().get_id() << std::endl; // 0x70000af43000}return 0;}
上面在实现 ThreadRAII 类的时候有一个小细节,std::thread 对象放到了 action 对象之后。这个与类的初始化列表有关,类的初始化列表会严格按照数据成员在类中声明的顺序来初始化成员。当类数据成员之间有关联的时候,要注意它们在类中的声明顺序。
🐰 总结
- 要保证 std::thread 对象在析构之前必须是 unjoinable 的
- 直接在 std::thread 对象的析构函数里面执行 join / detach 都会有问题
- 一个折中方案是在线程 RAII 包装类的析构函数里面执行 join / detach 操作
- 一个好消息是 C++20 引入的 std::jthread 解决了这里的所有问题
