【问题标题】:Multithreading not working (not faster than single threading)多线程不起作用(不比单线程快)
【发布时间】:2021-08-07 22:14:24
【问题描述】:

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

单线程:

long long summation(int start, int end)
{
    long long total = 0; 
    for (int i = start; i < end; i++)
    {
        total += i;
    }
    return total;
}

和多线程:

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
}

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

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

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

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

【问题讨论】:

  • 你读过get做什么
  • 您没有并行运行它。在get 中,它正在等待计算完成。
  • 这段代码没有正确使用多线程,只是增加了程序的复杂性,使其性能比单线程等效。等待异步操作完成基本上是一个同步操作。
  • 我确实阅读了get 所做的事情,但是任何有助于更好地理解我的错误的帮助都会奏效。也许是 get 正在停止代码?
  • 我怎样才能让它异步,而不使用 get?

标签: c++ multithreading asynchronous future


【解决方案1】:

通过立即调用.get(),您在任何时候都只运行一个线程。将std::future 收集到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;
}

【讨论】:

  • @cheveuxdelin 出于好奇,这次更改的基准时间是多少?
  • 使用 ryzen 9 4900 使用它的 16 个线程,我得到:单线程:994142226714070528,持续时间:1.23639 多线程:994142226714070528,持续时间:0.19740000000000000000000000000000000平均 600%
  • 所以大约 1/6 的时间需要 6 个内核......听起来似乎很合理 ;-)。哦,等等:8 核需要 1/6……更合理! (我的 6 核需要大约 1/5)。
【解决方案2】:

您需要存储期货并在最后求和。

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

  std::vector <std::future<long long>> results;
    for (int i = 0; i < numThreads; i++)
    {
        int start = summationRange * i;
        int end = summationRange * i + summationRange;
        results.emplace_back(async(launch::async, summation, start, end)) ; //The async function launches
    }

  // get the results from the futures then sum them
  //... 

    return total; //returns value
}

【讨论】:

  • @NathanOliver 抱歉,还没有在计算中。修复它。
猜你喜欢
  • 2016-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-22
  • 1970-01-01
  • 1970-01-01
  • 2018-09-11
相关资源
最近更新 更多