From 46bba78feb15eed9c2a304bf7a04e816d283f6e8 Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Wed, 6 Nov 2013 07:47:05 -0800 Subject: [PATCH] Avoid a mutex lock on a small parallel loop. --- thread/threadpool.cpp | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/thread/threadpool.cpp b/thread/threadpool.cpp index d79f2cd6c9..4524082e58 100644 --- a/thread/threadpool.cpp +++ b/thread/threadpool.cpp @@ -57,25 +57,26 @@ void ThreadPool::StartWorkers() { } void ThreadPool::ParallelLoop(std::function loop, int lower, int upper) { - mutex.lock(); - StartWorkers(); - int range = upper-lower; - if(range >= numThreads*2) { // don't parallelize tiny loops (this could be better, maybe add optional parameter that estimates work per iteration) + int range = upper - lower; + if (range >= numThreads * 2) { // don't parallelize tiny loops (this could be better, maybe add optional parameter that estimates work per iteration) + lock_guard guard(mutex); + StartWorkers(); + // could do slightly better load balancing for the generic case, // but doesn't matter since all our loops are power of 2 - int chunk = range/numThreads; + int chunk = range / numThreads; int s = lower; - for(int i=0; iProcess(std::bind(loop, s, s+chunk)); s+=chunk; } + // This is the final chunk. loop(s, upper); - for(int i=0; iWaitForCompletion(); } } else { loop(lower, upper); } - mutex.unlock(); }