64,651
社区成员
发帖
与我相关
我的任务
分享
#include <thread>
#include <stdexcept>
#include <iostream>
class scoped_thread {
std::thread t;
public:
explicit scoped_thread(std::thread && t_) :t(std::move(t_)) {
if (!t.joinable())
throw std::logic_error("No thread");
}
~scoped_thread() {
t.join();
std::cout << "destruct a thread" << std::endl;
}
scoped_thread(scoped_thread const &) = delete;
scoped_thread& operator=(scoped_thread const &) = delete;
//这下面的是我自己写的,没写完。移动构造器
scoped_thread(scoped_thread && t_) noexcept:t(std::move(t_.t)) { //t_.t = ;不会写了。。
}
//移动赋值运算符,也没写玩,不会写
scoped_thread& operator=(scoped_thread && t_) = default;
};
void funruninthread(){cout<<"hi"<<endl;}
void f(){
scoped_thread st{thread(funruninthread)};
}//这样在函数结束时会自动等待线程执行完毕
vector<scoped_thread> vst;
scoped_thread(scoped_thread const &) = delete;
scoped_thread& operator=(scoped_thread const &) = delete;