多线程不起作用(不比单线程快)

che*_*lin 0 c++ multithreading asynchronous future

我正在尝试使用一个简单的求和任务来测试多线程,我想在其中比较单线程与多线程。

单线程:

long long summation(int start, int end)
{
    long long total = 0; 
    for (int i = start; i < end; i++)
    {
        total += i;
    }
    return total;
}
Run Code Online (Sandbox Code Playgroud)

和多线程:

long long threadedSummation(int numThreads, int start, int end)
{
    long long total = 0;
    int summationRange = (start + end) / numThreads; //The range of numbers for every thread to calculate
    for (int i = 0; i < numThreads; i++)
    {
        int start = summationRange * i;
        int end = summationRange * i + summationRange;
        total += async(launch::async, summation, start, end).get(); //The async function launches
    }
    return total; //returns value
}
Run Code Online (Sandbox Code Playgroud)

问题是它没有更好的运行时间。测试 start = 0, end = 10000000000 我得到:

单线程:739026695568526336,持续时间:1.21866

多线程:739026695568526336,持续时间:1.28625

所以它不是更好,我认为代码一定有问题,我将不胜感激。

Pat*_*rts 5

通过立即调用,.get()您在任何时候都只运行一个线程。收集std::futurea std::vector,然后在创建所有这些之后,您可以.get()在它们并行运行后使用:

long long threadedSummation(int numThreads, int start, int end)
{
    long long total = 0;
    int summationRange = (start + end) / numThreads;
    std::vector<std::future<long long>> futures{};

    for (int i = 0; i < numThreads; i++)
    {
        int start = summationRange * i;
        int end = summationRange * i + summationRange;
        futures.emplace_back(async(launch::async, summation, start, end));
    }

    for (auto& future : futures)
    {
        total += future.get();
    }

    return total;
}
Run Code Online (Sandbox Code Playgroud)