0
点赞
收藏
分享

微信扫一扫

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

洲行 2022-04-22 阅读 48
c++

线程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 条评论