joinning_thread与std::thread 类似,但只要其执行析构函数线程就能自动汇合。
#include <iostream>
#include <thread>
class joinning_thread {
private:
std::thread t;
public:
joinning_thread() noexcept=default;
template<typename Callable, typename ... Args>
explicit joinning_thread(Callable&& func, Args&& ... args) : t(std::forward<Callable>(func), std::forward<Args>(args)...) {}
explicit joinning_thread(std::thread t_) noexcept: t(std::move(t_)) {}
joinning_thread(joinning_thread&& other) noexcept: t(std::move(other.t)) {}
joinning_thread& operator=(joinning_thread&& other) noexcept {
if (joinable()) {
join();
}
t = std::move(t);
return *this;
}
joinning_thread& operator=(std::thread other) noexcept {
if (joinable()) {
join();
}
t = std::move(t);
return *this;
}
~joinning_thread() noexcept {
if (joinable()) {
join();
}
}
bool joinable() const noexcept {
return t.joinable();
}
void join() {
t.join();
}
void detach() {
t.detach();
}
std::thread& as_thread() noexcept {
return t;
}
const std::thread& as_thread() const noexcept {
return t;
}
// 复制或赋值可能会带来问题 不得自动生成
joinning_thread(joinning_thread const&) = delete;
joinning_thread& operator=(joinning_thread const&) = delete;
};
int main() {
return 0;
}
No comments yet.