溫馨提示×

c++ exec如何設置超時

c++
小樊
130
2024-12-01 15:56:14
欄目: 編程語言

在C++中,你可以使用<chrono>庫和<thread>庫來設置一個執行特定任務時的超時

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

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

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

    // 啟動一個線程來執行異步任務
    std::thread task_thread(std::move(task));

    // 設置超時時間(單位:毫秒)
    int timeout = 3000;

    // 等待任務完成或達到超時時間
    if (result.wait_for(std::chrono::milliseconds(timeout)) == std::future_status::ready) {
        // 任務在超時時間內完成,獲取任務結果
        int value = result.get();
        std::cout << "Task completed with result: " << value << std::endl;
    } else {
        // 任務超時,取消任務
        task_thread.join(); // 等待任務線程結束
        std::cout << "Task timed out" << std::endl;
    }

    return 0;
}

在這個示例中,我們創建了一個異步任務,該任務會模擬一個耗時5秒的操作。我們使用std::packaged_task來包裝任務,然后通過std::future對象來獲取任務的結果。我們設置了一個3秒的超時時間,如果任務在3秒內完成,我們將獲取任務結果并輸出;否則,我們將取消任務并輸出超時信息。

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