2012-10-10 17 views
1

我是C++的新手,還沒有在C++中使用任何線程。我在使用Visual Studio中的Windows 7 2010年C++:如何運行系統命令N次(異步)並獲取N次執行時間?

我試圖做的是寫觸發一個給定的系統命令氮處決和每次執行它能夠獲得所爲,時間主要方法完成時的特定執行。通過獲得該命令的返回碼,知道命令是成功還是失敗也是很好的,並且作爲獎勵獲得輸出返回將是很好的,儘管不是最初必需的。

現在我知道如何做到這一點,但考慮到我需要在同一時間產生N個執行,並且每個執行都可能是長時間運行,我猜測每個執行都需要一個線程,而這個是我不知道該怎麼做的。

對於人新的C++線程請你選擇一個線程執行和庫,你想推薦給我的怎麼辦上述一例的主要方法是什麼?隨後我也將閱讀C++線程(如果您有任何關於資源的指示,請讓我知道)。非常感謝。

+0

對於螺紋見['的std :: thread'](http://en.cppreference.com/w/cpp/thread/thread),用於在Windows中調用外部程序請參見['CreateProcess'](http://msdn.microsoft.com/en-us/library/windows/desktop/ms682425%28v=vs.85%29.aspx )。 –

+0

然而,在你的情況下,當線程應該返回一個值,你應該看看['標準:: future'(http://en.cppreference.com/w/cpp/thread/future)和['的std :: async'](http://en.cppreference.com/w/cpp/thread/async)。 –

+0

@JoachimPileborg謝謝。 VS找不到'#include '也沒有'#include '。這需要什麼樣的庫?我以爲它已經在stdlib中了? – junkie

回答

4

下面是使用一個小程序從C++ 11新threading functionality

#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"; 
    } 
} 
+0

謝謝'thread','future'和'chrono'包括不能在我的VS2010中找到。我需要做什麼讓這些? – junkie

+0

不幸的是,OP用途VC10,它沒有C++ 11線程設施,但仍然+1,當然 –

+0

@junkie那麼你有兩個選擇:一是尋找具有線程一些多平臺庫([Qt的(HTTP:/ /qt-project.org/)很受歡迎,但可能是矯枉過正);第二個是使用本地線程,請參閱[本頁](http://msdn.microsoft.com/zh-cn/library/windows/desktop /ms682516%28v=vs.85%29.aspx)的一個例子。 –