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 は、あらゆる Callable ターゲット(関数、ラムダ式、バインド式、または他の関数オブジェクト)をラップし、非同期で呼び出せるようにします。その戻り値またはスローされた例外は共有状態に格納され、 std::future オブジェクトを通じてアクセスできます。

std::function と同様に、 std::packaged_task はポリモーフィックでアロケータ対応のコンテナです:格納された呼び出し可能ターゲットは、ヒープ上または提供されたアロケータを使用して割り当てられる可能性があります。

(until C++17)

目次

メンバー関数

タスクオブジェクトを構築する
(public member function)
タスクオブジェクトを破棄する
(public member function)
タスクオブジェクトを移動する
(public member function)
タスクオブジェクトが有効な関数を持っているかチェックする
(public member function)
2つのタスクオブジェクトを交換する
(public member function)
結果の取得
約束された結果に関連付けられた std::future を返す
(public member function)
実行
関数を実行する
(public member function)
現在のスレッドが終了した時点でのみ結果が準備完了となることを保証して関数を実行する
(public member function)
状態をリセットし、以前の実行で保存された結果を破棄する
(public member function)

非メンバー関数

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++規格に対して遡及的に適用されました。

DR 適用対象 公開時の動作 正しい動作
LWG 3117 C++17 packaged_task のデダクションガイドが欠落していた 追加された

関連項目

(C++11)
非同期に設定される値を待機する
(クラステンプレート)