簡體   English   中英

C ++:如何運行系統命令N次(異步)並返回N次執行時間?

[英]C++: How to run a system command N times (async) and get N execution times back?

我是C ++的新手,還沒有在C ++中使用任何線程。 我在Windows 7上使用visual studio 2010。

我正在嘗試做的是編寫一個主方法來觸發給定系統命令的N次執行,並且對於每次執行,它都能夠獲得完成時特定執行所花費的時間。 通過獲取該命令的返回代碼來了解命令是成功還是失敗也是很好的,並且作為獎勵獲得輸出將是好的,盡管最初不是必要的。

現在我知道如何完成大部分工作,但考慮到我需要同時生成N次執行,並且假設每次執行都可能長時間運行,我猜它每次執行都需要一個線程,這就是我的意思我不知道該怎么做。

對於那些剛接觸C ++線程的人,請你選擇一個你想推薦的線程實現和庫,並給我一個示例如何執行上述操作的主要方法? 我將隨后閱讀C ++線程(如果您對資源有任何指示,請告訴我)。 非常感謝。

這是一個使用C ++ 11新線程功能的小程序:

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

std::chrono::nanoseconds run_program_and_calculate_time()
{
    // TODO: Do your real stuff here
    return std::chrono::nanoseconds(5);
}

int main()
{
    constexpr int N = 5;

    std::vector<std::future<std::chrono::nanoseconds>> results(N);

    // Start the threads
    for (int i = 0; i < N; i++)
    {
        results[i] = std::async(std::launch::async,
                [](){ return run_program_and_calculate_time(); });
    }

    // Wait for all threads to be done results
    for (int i = 0; i < N; i++)
        results[i].wait();

    // Print results
    for (int i = 0; i < N; i++)
    {
        std::cout << "Result from " << i << ": "
                      << results[i].get().count() << " nanoseconds\n";
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM