线程scoped在某些场合还是很有用的,可以简化编程,不易出错。示例如下:
#include <exception>
#include <iostream>
#include <thread>
struct scoped_thread
{
std::thread th;
scoped_thread(std::thread&& t)
{
if (!t.joinable())
throw std::runtime_error("thread not joinable");
th = std::move(t);
}
~scoped_thread()
{
if (th.joinable())
th.join();
}
};
void func()
{
std::cout << "you mean that you are a hacker out of the matrix?" << std::endl;
}
int main()
{
std::thread t(func);
scoped_thread st(std::move(t));
std::cout << "let me guess what you will ask me." << std::endl;
return 0;
}