【问题标题】:Low performance of boost::barrier, wait operationboost::barrier、wait操作的性能低下
【发布时间】:2014-07-31 22:05:46
【问题描述】:

我遇到了 boost:barrier 的性能问题。我测量了等待方法调用的时间,对于单线程情况,当调用等待重复大约 100000 次时,大约需要 0.5 秒。不幸的是,对于两个线程场景,这个时间扩展到 3 秒,并且每个线程都变得更糟(我有 8 个核心处理器)。

我实现了负责提供相同功能的自定义方法,而且速度更快。

这种方法工作这么慢是正常的吗。有没有更快的方式来同步boost中的线程(所以所有线程都等待所有线程完成当前作业,然后继续下一个任务,只是同步,不需要数据传输)。

有人询问我当前的代码。 我想要达到的目标。在一个循环中我运行一个函数,这个函数可以分成许多线程,但是所有线程都应该在执行另一个运行之前完成当前循环运行。

我目前的解决方案

volatile int barrierCounter1 =0; //it will store number of threads which completed current loop run
volatile bool barrierThread1[NumberOfThreads]; //it will store go signal for all threads with id > 0. All values are set to false at the beginning
boost::mutex mutexSetBarrierCounter; //mutex for barrierCounter1 modification

void ProcessT(int threadId)
{
    do
    {
      DoWork(); //function which should be executed by every thread

      mutexSetBarrierCounter.lock();
      barrierCounter1++;  //every thread notifies that it finish execution of function
      mutexSetBarrierCounter.unlock();

      if(threadId == 0)
      {
        //main thread (0) awaits for completion of all threads
        while(barrierCounter1!=NumberOfThreads)
        {
        //I assume that the number of threads is lower than the number of processor cores
        //so this loop should not have an impact of overall performance
        }
        //if all threads completed, notify other thread that they can proceed to the consecutive loop
        for(int i = 0; i<NumberOfThreads; i++)
        {
          barrierThread1[i] = true;
        }
        //clear counter, no lock is utilized because rest of threads await in else loop
        barrierCounter1 = 0;
      }
      else
      {
      //rest of threads await for "go" signal
        while(barrierThread1[i]==false)
        {

        }
        //if thread is allowed to proceed then it should only clean up its barrier thread array
        //no lock is utilized because '0' thread would not modify this value until all threads complete loop run
        barrierThread1[i] = false;
      }
}
while(!end)
}

【问题讨论】:

  • “我实现了负责提供相同功能的自定义方法,而且速度更快” - 如果你展示了这个,我们可能会解释为什么它更快(以及它是否正确)

标签: c++ multithreading performance boost


【解决方案1】:

锁定与并发背道而驰。锁定争用总是最糟糕的行为。

IOW:线程同步(本身)永远不会扩展。

解决方案:仅在争用较低的情况下使用同步原语(线程需要“相对很少”同步[1]),不要尝试为争夺共享资源的作业使用多个线程。

您的基准测试似乎放大了最坏情况下的行为,让所有线程始终等待。如果障碍之间的所有工作人员都有大量工作量,那么开销就会减少,并且很容易变得微不足道。

  • 相信你的分析器
  • 仅分析您的应用程序代码(没有 silly 综合基准测试)
  • 更喜欢非线程而不是线程(记住:异步 != 并发)

[1]这是高度相对和主观的

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-15
    • 2011-11-03
    • 2019-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多