c++ - boost::barrier性能低,等待操作

标签 c++ multithreading performance boost

我遇到了 boost:barrier 的性能问题。我测量了 wait 方法调用的时间,对于单线程情况,当 wait 调用重复大约 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)
}

最佳答案

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

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

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

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

  • 相信你的分析器
  • 仅分析您的应用程序代码(没有愚蠢的综合基准)
  • 首选非线程而不是线程(记住:异步!= 并发)

[1] 高度相关和主观

关于c++ - boost::barrier性能低,等待操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24152929/

相关文章:

c++ - 禁止在类内使用方法

c++ - 如何扩展对可变参数模板基类的调用?

c++ - 编译我的第一个 C++ 程序时遇到问题

java - 在 Java 中,如何确定守护线程始终在运行?

c++ - pthread 返回 251

sql-server - SQL Server : Improve PROCEDURE without using CURSOR

c++ - 没有 typedef 的运算符 member_function_pointer_type()?

c# - ASP.NET Core线程中默认的IServiceProvider安全吗?

Java快速像素操作

eclipse 持续减速