std::packaged_task
提供: cppreference.com
<tbody>
</tbody>
| ヘッダ <future> で定義
|
||
template< class > class packaged_task; //not defined |
(1) | (C++11以上) |
template< class R, class ...Args > class packaged_task<R(Args...)>; |
(2) | (C++11以上) |
クラステンプレート std::packaged_task は、任意の Callable なターゲット (関数、ラムダ式、バインド式、または別の関数オブジェクト) を、非同期に呼ぶことができるようにラップします。 その戻り値または投げられた例外は、 std::future オブジェクトを通してアクセスできる共有状態に格納されます。
|
std::function と同様、 |
(C++17未満) |
メンバ関数
| タスクオブジェクトを構築します (パブリックメンバ関数) | |
| タスクオブジェクトを破棄します (パブリックメンバ関数) | |
| タスクオブジェクトをムーブします (パブリックメンバ関数) | |
| タスクオブジェクトが有効な関数を持っているか調べます (パブリックメンバ関数) | |
| 2つのタスクオブジェクトを入れ替えます (パブリックメンバ関数) | |
結果の取得 | |
| 約束された結果に紐付けられた std::future を返します (パブリックメンバ関数) | |
実行 | |
| 関数を実行します (パブリックメンバ関数) | |
| 関数を実行し、カレントスレッドの終了後にのみ結果が準備完了になるようにします (パブリックメンバ関数) | |
| 格納されている以前の実行の結果をすべて破棄し、状態をリセットします (パブリックメンバ関数) | |
非メンバ関数
| std::swap アルゴリズムの特殊化 (関数テンプレート) |
ヘルパークラス
(C++11)(C++17未満) |
std::uses_allocator 型特性の特殊化 (クラステンプレートの特殊化) |
例
Run this code
#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) |
非同期に設定される値を待ちます (クラステンプレート) |