Namespaces
Variants

std:: packaged_task

From cppreference.net
Concurrency support library
Threads
(C++11)
(C++20)
this_thread namespace
(C++11)
(C++11)
Cooperative cancellation
Mutual exclusion
Generic lock management
Condition variables
(C++11)
Semaphores
Latches and Barriers
(C++20)
(C++20)
Futures
(C++11)
(C++11)
packaged_task
(C++11)
(C++11)
Safe reclamation
Hazard pointers
Atomic types
(C++11)
(C++20)
Initialization of atomic types
(C++11) (deprecated in C++20)
(C++11) (deprecated in C++20)
Memory ordering
(C++11) (deprecated in C++26)
Free functions for atomic operations
Free functions for atomic flags
定义于头文件 <future>
template < class >
class packaged_task ;
(1) (C++11 起)
(未定义)
template < class R, class ... ArgTypes >
class packaged_task < R ( ArgTypes... ) > ;
(2) (C++11 起)

类模板 std::packaged_task 封装任意 可调用对象 目标(函数、lambda表达式、绑定表达式或其他函数对象),使其能够被异步调用。其返回值或抛出的异常存储于共享状态中,该状态可通过 std::future 对象访问。

std::function 类似, std::packaged_task 是一个多态且支持分配器感知的容器:存储的可调用目标可以通过堆分配或使用提供的分配器进行分配。

(C++17 前)

目录

成员函数

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

非成员函数

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

辅助类

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

推导指引 (C++17 起)

示例

#include <cmath>
#include <functional>
#include <future>
#include <iostream>
#include <thread>
// 独立函数以避免与 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++标准。

缺陷报告 应用于 发布时的行为 正确行为
LWG 3117 C++17 packaged_task 的推导指引缺失 已添加

参见

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