1

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

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

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

对于 C++ 线程的新手,请您选择一个您想推荐的线程实现和库,并给我一个示例主要方法来说明如何执行上述操作?我随后也会阅读 C++ 线程(如果您对资源有任何指示,请告诉我)。非常感谢。

4

1 回答 1

4

这是一个使用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";
    }
}
于 2012-10-10T11:23:16.847 回答