名稱空間
變體
操作

std::packaged_task<R(Args...)>::make_ready_at_thread_exit

來自 cppreference.com
 
 
併發支援庫
執行緒
(C++11)
(C++20)
this_thread 名稱空間
(C++11)
(C++11)
(C++11)
協同取消
互斥
(C++11)
通用鎖管理
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
條件變數
(C++11)
訊號量
門閂和屏障
(C++20)
(C++20)
期值
(C++11)
(C++11)
(C++11)
(C++11)
安全回收
(C++26)
危險指標
原子型別
(C++11)
(C++20)
原子型別的初始化
(C++11)(C++20 中已棄用)
(C++11)(C++20 中已棄用)
記憶體排序
(C++11)(C++26 中已棄用)
原子操作的自由函式
原子標誌的自由函式
 
 
void make_ready_at_thread_exit( ArgTypes... args );
(C++11 起)

呼叫儲存的任務,如同透過 INVOKE<R>(f, args...),其中 f 是儲存的任務。任務的返回值或其丟擲的任何異常都儲存在 *this 的共享狀態中。

共享狀態僅在當前執行緒退出且所有具有執行緒區域性儲存持續時間的物件被銷燬後才變為就緒。

目錄

[編輯] 引數

args - 呼叫儲存任務時要傳遞的引數

[編輯] 返回值

(無)

[編輯] 異常

對於下列錯誤條件丟擲 std::future_error

  • 已呼叫儲存的任務。錯誤類別設定為 promise_already_satisfied
  • *this 無共享狀態。錯誤類別設為 no_state

[編輯] 示例

#include <chrono>
#include <functional>
#include <future>
#include <iostream>
#include <memory>
#include <thread>
#include <utility>
 
struct ProgramState
{
    std::packaged_task<void()> task;
    std::future<void> future;
    std::thread worker;
};
 
static void worker(std::shared_ptr<ProgramState> state)
{
    state->task.make_ready_at_thread_exit(); // execute task right away
 
    auto status = state->future.wait_for(std::chrono::seconds(0));
    if (status == std::future_status::timeout)
        std::cout << "worker: future is not ready yet\n";
    else
        std::cout << "worker: future is ready\n";
 
    std::cout << "worker: exit\n";
}
 
static std::shared_ptr<ProgramState> create_state()
{
    auto state = std::make_shared<ProgramState>();
    state->task = std::packaged_task<void()>{[]
    {
        std::cout << "task: executed\n";
    }};
    state->future = state->task.get_future();
    state->worker = std::thread{worker, state};
    return state;
}
 
int main()
{
    auto state = create_state();
 
    state->worker.join();
    std::cout << "main: worker finished\n";
 
    auto status = state->future.wait_for(std::chrono::seconds(0));
    if (status == std::future_status::timeout)
        std::cout << "main: future is not ready yet\n";
    else
        std::cout << "main: future is ready\n";
}

輸出

task: executed
worker: future is not ready yet
worker: exit
main: worker finished
main: future is ready

[編輯] 參閱

執行函式
(公共成員函式) [編輯]