首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::packaged_task

Defined in header <future>

?

?

template< class > class packaged_task; //not defined

(1)

(since C++11)

template< class R, class ...Args > class packaged_task<R(Args...)>;

(2)

(since C++11)

类模板std::packaged_task包任何Callable目标%28函数、lambda表达式、绑定表达式或其他函数对象%29,以便可以异步调用它。其返回值或抛出的异常以共享状态存储,可通过std::future物品。

就像std::function,,,std::packaged_task是一个多态的、分配器感知的容器:存储的可调用目标可以在堆上分配,也可以用提供的分配器分配。

成员函数

(constructor)

constructs the task object (public member function)

(destructor)

destructs the task object (public member function)

operator=

moves the task object (public member function)

valid

checks if the task object has a valid function (public member function)

swap

swaps two task objects (public member function)

得到结果

弄到[医]返回一个std::未来与承诺的结果%28公共成员函数%29相关联

执行

操作符%28%29执行函数%28公共成员函数%29

制造[医]准备好了[医]在[医]螺纹[医]Exit执行该函数,确保只在当前线程退出%28公共成员函数%29时才准备好结果。

重置重置状态,放弃以前执行的任何存储结果%28公共成员函数%29

非会员职能

std::swap(std::packaged_task) (C++11)

specializes the std::swap algorithm (function template)

帮助者类

std::uses_allocator<std::packaged_task> (C++11)(until C++17)

specializes the std::uses_allocator type trait (class template specialization)

二次

代码语言:javascript
复制
#include <iostream>
#include <cmath>
#include <thread>
#include <future>
#include <functional>
 
// unique function to avoid disambiguating the std::pow overload set
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();
}

二次

产出:

二次

代码语言:javascript
复制
task_lambda: 512
task_bind:   2048
task_thread: 1024

二次

另见

future (C++11)

waits for a value that is set asynchronously (class template)

代码语言:txt
复制
 ? cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com