C ++:如何运行系统命令N次(异步)并返回N次执行时间?

时间:2012-10-10 10:47:32

标签: c++ c multithreading

我是C ++的新手,还没有在C ++中使用任何线程。我在Windows 7上使用visual studio 2010。

我要做的是编写一个主方法来触发给定系统命令的N次执行,并且对于每次执行,它都能够获得完成时特定执行所花费的时间。通过获取该命令的返回代码来了解命令是成功还是失败也是很好的,并且作为奖励获得输出将是好的,虽然最初不是必需的。

现在我知道如何完成大部分工作,但考虑到我需要同时生成N次执行,并且假设每次执行都可能长时间运行,我猜它每次执行都需要一个线程,这是我不知道该怎么做。

对于初次使用C ++线程的人,请选择您想要推荐的线程实现和库,并举例说明如何执行上述操作的主要方法?我将随后阅读C ++线程(如果您对资源有任何指示,请告诉我)。非常感谢。

1 个答案:

答案 0 :(得分: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";
    }
}