溫馨提示×

c++ wait_for如何實現

c++
小樊
92
2024-11-24 11:57:50
欄目: 編程語言

wait_for 是 C++11 標準庫 <future> 中的一個函數,它用于等待一個異步操作完成

#include <iostream>
#include <chrono>
#include <thread>
#include <future>

int main() {
    // 創建一個異步任務
    std::packaged_task<int()> task([](){
        std::this_thread::sleep_for(std::chrono::seconds(2)); // 模擬耗時操作
        return 42; // 返回結果
    });

    // 獲取異步任務的 future 對象
    std::future<int> result = task.get_future();

    // 在一個新線程中運行異步任務
    std::thread task_thread(std::move(task));
    task_thread.detach();

    // 等待異步任務完成,最多等待 3 秒
    if (result.wait_for(std::chrono::seconds(3)) == std::future_status::ready) {
        // 獲取異步任務的結果
        int value = result.get();
        std::cout << "異步任務返回結果: " << value << std::endl;
    } else {
        std::cout << "異步任務未完成,已超時" << std::endl;
    }

    return 0;
}

在這個示例中,我們創建了一個異步任務,該任務會休眠 2 秒并返回結果。我們使用 get_future() 獲取異步任務的 future 對象,然后在一個新線程中運行該任務。接下來,我們使用 wait_for() 函數等待異步任務完成,最多等待 3 秒。如果異步任務在 3 秒內完成,我們將獲取并輸出其結果;否則,我們將輸出任務未完成的消息。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女