C++并发编程练习07 “线程管理之线程scoped”

洲行

关注

阅读 48

2022-04-22

线程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;
}

精彩评论(0)

0 0 举报