From 85b24bb2dea97c3a9b013bacd5a422b26fe5d14b Mon Sep 17 00:00:00 2001 From: David Faure Date: Mon, 19 Aug 2013 10:45:06 +0200 Subject: QThreadPool: fix data races in activeThreadCount() Rather than trying to make it lock-free (which requires double-bookkeeping of 4 atomic ints!), just lock the mutex before calling it. tst_bench_qthreadpool shows no difference whatsoever between the two solutions, I get 0.005 msecs per iteration in startRunnables(). Of course looping over calls to activeThreadCount() is a bit slower, from 0.0002 msecs per iteration to 0.00027 msecs, i.e. 35% more. But polling activeThreadCount() from the app is a really wrong thing to do anyway, this benchmark was just for my own curiosity about the price of a mutex in a function that sums up 4 ints. What matters is start() performance, which is unchanged (0.00007 msecs is just noise compared to a 0.005 total, that's 1.4%). Change-Id: I993444eef8bc68eff9badd581fae3626dfd1cc6d Reviewed-by: Olivier Goffart --- src/corelib/thread/qthreadpool.cpp | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/corelib/thread/qthreadpool.cpp b/src/corelib/thread/qthreadpool.cpp index b9427666b6..31c3f5a256 100644 --- a/src/corelib/thread/qthreadpool.cpp +++ b/src/corelib/thread/qthreadpool.cpp @@ -223,8 +223,6 @@ void QThreadPoolPrivate::enqueueTask(QRunnable *runnable, int priority) int QThreadPoolPrivate::activeThreadCount() const { - // To improve scalability this function is called without holding - // the mutex lock -- keep it thread-safe. return (allThreads.count() - expiredThreads.count() - waitingThreads @@ -485,12 +483,11 @@ bool QThreadPool::tryStart(QRunnable *runnable) Q_D(QThreadPool); - // To improve scalability perform a check on the thread count - // before locking the mutex. + QMutexLocker locker(&d->mutex); + if (d->allThreads.isEmpty() == false && d->activeThreadCount() >= d->maxThreadCount) return false; - QMutexLocker locker(&d->mutex); return d->tryStart(runnable); } @@ -564,6 +561,7 @@ void QThreadPool::setMaxThreadCount(int maxThreadCount) int QThreadPool::activeThreadCount() const { Q_D(const QThreadPool); + QMutexLocker locker(&d->mutex); return d->activeThreadCount(); } -- cgit v1.2.3