std::packaged_task
C++11引入的模板类,用于封装可调用对象,以便异步执行该任务,并且可以通过std::future获取结果。通常与线程池一起使用。
主要成员函数:
get_future():返回一个std::future对象,用于获取任务的结果。
operator():执行封装的任务。
reset():重置任务。使其可以被重复使用。(如果在任务执行过程中重置任务将会抛出异常)
使用案例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| #include <iostream> #include <thread> #include <future> #include <chrono>
int calculateSum(int a, int b) { std::this_thread::sleep_for(std::chrono::seconds(2)); std::cout << "thread executing" << std::endl; return a + b; }
int main() { std::packaged_task<int(int, int)> task(calculateSum);
std::future<int> result = task.get_future();
std::thread t(std::ref(task), 10, 20);
std::cout << "Task is being executed asynchronously..." << std::endl;
std::cout << "The result of the task is: " << result.get() << std::endl;
t.join();
task.reset(); std::thread t1(std::ref(task), 10, 20); t1.join(); task.reset(); task();
return 0; }
|
注意:传递std::packaged_task时,必须使用std::move或者std::ref,因为packaged_task的拷贝构造函数不可用。