std::packaged_task

定义于头文件 <future>
template< class > class packaged_task; // 不定义
(1) (C++11 起)
template< class R, class ...Args >
class packaged_task<R(Args...)>;
(2) (C++11 起)

类模板 std::packaged_task 包装任何可调用 (Callable) 目标(函数、 lambda 表达式、 bind 表达式或其他函数对象),使得能异步调用它。其返回值或所抛异常被存储于能通过 std::future 对象访问的共享状态中。

正如 std::functionstd::packaged_task 是多态、具分配器的容器:可在堆上或以提供的分配器分配存储的可调用对象。

目录

成员函数

构造任务对象
(公开成员函数)
析构任务对象
(公开成员函数)
移动任务对象
(公开成员函数)
检查任务对象是否拥有合法函数
(公开成员函数)
交换二个任务对象
(公开成员函数)
获取结果
返回与承诺的结果关联的 std::future
(公开成员函数)
执行
执行函数
(公开成员函数)
执行函数,并确保结果仅在一旦当前线程退出时就绪
(公开成员函数)
重置状态,抛弃任何先前执行的存储结果
(公开成员函数)

非成员函数

特化 std::swap 算法
(函数模板)

帮助类

特化 std::uses_allocator 类型特性
(类模板特化)

示例

#include <iostream>
#include <cmath>
#include <thread>
#include <future>
#include <functional>
 
// 避免对 std::pow 重载集消歧义的独有函数
int f(int x, int y) { return std::pow(x,y); }
 
void task_lambda()
{
    std::packaged_task<int(int,int)> task([](int a, int b) {
        return std::pow(a, b); 
    });
    std::future<int> result = task.get_future();
 
    task(2, 9);
 
    std::cout << "task_lambda:\t" << result.get() << '\n';
}
 
void task_bind()
{
    std::packaged_task<int()> task(std::bind(f, 2, 11));
    std::future<int> result = task.get_future();
 
    task();
 
    std::cout << "task_bind:\t" << result.get() << '\n';
}
 
void task_thread()
{
    std::packaged_task<int(int,int)> task(f);
    std::future<int> result = task.get_future();
 
    std::thread task_td(std::move(task), 2, 10);
    task_td.join();
 
    std::cout << "task_thread:\t" << result.get() << '\n';
}
 
int main()
{
    task_lambda();
    task_bind();
    task_thread();
}

输出:

task_lambda: 512
task_bind:   2048
task_thread: 1024

参阅

(C++11)
等待被异步设置的值
(类模板)

版本历史

  • (当前 | 先前 2017年9月25日 (一) 01:16Fruderica讨论 | 贡献. . (2,717字节) (-238). . (撤销)
  • 当前 | 先前 2013年7月2日 (二) 11:32P12bot讨论 | 贡献 . . (2,955字节) (-296). . (Use {{lc}}. Update links. Various fixes.) (撤销)
  • 当前 | 先前 2012年11月2日 (五) 19:31P12bot讨论 | 贡献 . . (3,251字节) (+257). . (r2.7.3) (机器人添加:de, en, es, fr, it, ja, pt, ru) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 03:08P12讨论 | 贡献 . . (2,994字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前) 2012年10月25日 (四) 12:00TranslationBot讨论 | 贡献. . (2,994字节) (+2,994). . (Translated from the English version using Google Translate)