std::packaged_task
From cppreference.com
| ヘッダ <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ターゲット(関数、ラムダ式、bind式、または他の関数オブジェクト)をラップし、非同期に呼び出せるようにします。その戻り値またはスローされた例外は共有状態に格納され、std::futureオブジェクトを通じてアクセスできます。
|
|
(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 アルゴリズムを特殊化する (関数テンプレート) |
[編集] ヘルパークラス
| (C++11) (C++17まで) |
std::uses_allocator 型特性を特殊化する (クラステンプレート特殊化) |
[編集] 推論ガイド (C++17以降)
[編集] 例
このコードを実行
#include <cmath> #include <functional> #include <future> #include <iostream> #include <thread> // 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(); }
出力
task_lambda: 512 task_bind: 2048 task_thread: 1024
[編集] 不具合報告
以下の動作変更を伴う欠陥報告が、以前に公開されたC++標準に遡って適用されました。
| DR | 適用対象 | 公開された動作 | 正しい動作 |
|---|---|---|---|
| LWG 3117 | C++17 | packaged_taskの推論ガイドが欠落していました |
追加された |
[編集] 関連項目
| (C++11) |
非同期に設定される値を待機する (クラステンプレート) |