C++11 packaged_task

std::packaged_task 把一个方法打包成一个task扔到线程中执行,然后通过packaged_task中的furture等待执行结果。

void test_promise()
{
	std::packaged_task  task([]()->int {
		std::cout << "packaged_task begin \n" << std::endl;
		std::this_thread::sleep_for(std::chrono::seconds(3));
		std::cout << "packaged_task end \n" << std::endl; 
		return 0; 
		});
	std::future fret = task.get_future();
	std::thread t3(std::move(task));
	
	int ret = fret.get();
	std::cout << "packaged_task ret:" << ret  << std::endl;

	t3.join();
}

template
void test_forword(F f, Types ... args)
{
	auto func = std::bind(std::forward(f), std::forward(args)...);
	//func(); return;
	using ret_type = typename std::result_of::type;
	std::packaged_task  task(func);

	std::future fret = task.get_future();
	std::thread t4(std::move(task));

	int ret = fret.get();
	std::cout << "forword bind task ret:" << ret << std::endl;

	t4.join();
}

int forword_task(int a, int b)
{
	std::cout << "forword_task a:" << a << std::endl;
	std::cout << "forword_task b:" << b << std::endl;
	return a + b;
}

class Forward
{
public:
	int forword_task(int a, int b)
	{
		std::cout << "forword_task a:" << a << std::endl;
		std::cout << "forword_task b:" << b << std::endl;
		return a + b;
	}
};

int main()
{
	test_forword(forword_task, 10, 20);

	Forward fw;
	test_forword(&Forward::forword_task, &fw, 30, 40);
	return 0;
	
	test_promise();
	return 0;
}

你可能感兴趣的:(c++,开发语言)