std::packaged_task 把一个方法打包成一个task扔到线程中执行,然后通过packaged_task中的furture等待执行结果。
void test_promise()
{
std::packaged_task <int()> 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<int> 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<typename F, typename ... Types>
void test_forword(F f, Types ... args)
{
auto func = std::bind(std::forward<F>(f), std::forward<Types>(args)...);
//func(); return;
using ret_type = typename std::result_of<F(Types...)>::type;
std::packaged_task <ret_type()> task(func);
std::future<ret_type> 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;
}