std::packaged_task
來自 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) 目標(函式、lambda 表示式、bind 表示式或其他函式物件),使其可以非同步呼叫。其返回值或丟擲的異常儲存在一個共享狀態中,該狀態可以透過 std::future 物件訪問。
與 std::function 類似, |
(C++17 前) |
目錄 |
[編輯] 成員函式
構造任務物件 (public member function) | |
銷燬任務物件 (public member function) | |
移動任務物件 (public member function) | |
檢查任務物件是否有有效函式 (public member function) | |
交換兩個任務物件 (public member function) | |
Getting the result | |
返回與承諾結果關聯的 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++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 3117 | C++17 | 缺少 packaged_task 的推導指南 |
已新增 |
[編輯] 參閱
(C++11) |
等待一個非同步設定的值 (類模板) |