简体   繁体   English

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

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

I'm new to C++ and have not used any threading in C++ yet. 我是C ++的新手,还没有在C ++中使用任何线程。 I'm on windows 7 using visual studio 2010. 我在Windows 7上使用visual studio 2010。

What I'm trying to do is write a main method that triggers N executions of a given system command and for each execution it is able to acquire the time taken for that particular execution on completion. 我正在尝试做的是编写一个主方法来触发给定系统命令的N次执行,并且对于每次执行,它都能够获得完成时特定执行所花费的时间。 It would also be nice to know if the command succeeded or failed through getting the return code for that command and as a bonus getting the output back would be nice although not essential initially. 通过获取该命令的返回代码来了解命令是成功还是失败也是很好的,并且作为奖励获得输出将是好的,尽管最初不是必要的。

Now I know how to do most of this but given that I need to spawn N executions at the same time and given that each execution is likely to be long running I'm guessing it will need a thread per execution and this is what I'm not sure how to do. 现在我知道如何完成大部分工作,但考虑到我需要同时生成N次执行,并且假设每次执行都可能长时间运行,我猜它每次执行都需要一个线程,这就是我的意思我不知道该怎么做。

For someone new to C++ threading would you please choose a threading implementation and library that you'd like to recommend and give me an example main method of how to do the above? 对于那些刚接触C ++线程的人,请你选择一个你想推荐的线程实现和库,并给我一个示例如何执行上述操作的主要方法? I will be reading on C++ threading too subsequently (if you have any pointers on resources please let me know). 我将随后阅读C ++线程(如果您对资源有任何指示,请告诉我)。 Many thanks. 非常感谢。

Here's a small program using the new threading functionality from C++11: 这是一个使用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