【发布时间】: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