From eaee1209f0ead5be786e81db8aee604ccfea85b0 Mon Sep 17 00:00:00 2001 From: Allan Sandfeld Jensen Date: Wed, 12 Apr 2017 17:34:41 +0200 Subject: Switch QSemaphore::tryAcquire to using QDeadlineTimer A deadline timer is more correct for timeouts. Also starts the timer before trying to acquire the mutex for more precise timeouts. Task-number: QTBUG-58745 Change-Id: I230266a3a5d7b7af33981efed4e6882e5727a41c Reviewed-by: Thiago Macieira --- src/corelib/thread/qsemaphore.cpp | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) (limited to 'src') diff --git a/src/corelib/thread/qsemaphore.cpp b/src/corelib/thread/qsemaphore.cpp index 8427b0e696..ce0c1c91df 100644 --- a/src/corelib/thread/qsemaphore.cpp +++ b/src/corelib/thread/qsemaphore.cpp @@ -42,7 +42,7 @@ #ifndef QT_NO_THREAD #include "qmutex.h" #include "qwaitcondition.h" -#include "qelapsedtimer.h" +#include "qdeadlinetimer.h" #include "qdatetime.h" QT_BEGIN_NAMESPACE @@ -214,20 +214,19 @@ bool QSemaphore::tryAcquire(int n) bool QSemaphore::tryAcquire(int n, int timeout) { Q_ASSERT_X(n >= 0, "QSemaphore::tryAcquire", "parameter 'n' must be non-negative"); + if (timeout < 0) + return tryAcquire(n); + + QDeadlineTimer timer(timeout); QMutexLocker locker(&d->mutex); - if (timeout < 0) { - while (n > d->avail) - d->cond.wait(locker.mutex()); - } else { - QElapsedTimer timer; - timer.start(); - while (n > d->avail) { - const qint64 elapsed = timer.elapsed(); - if (timeout - elapsed <= 0 - || !d->cond.wait(locker.mutex(), timeout - elapsed)) - return false; - } + qint64 remainingTime = timer.remainingTime(); + while (n > d->avail && remainingTime > 0) { + if (!d->cond.wait(locker.mutex(), remainingTime)) + return false; + remainingTime = timer.remainingTime(); } + if (n > d->avail) + return false; d->avail -= n; return true; -- cgit v1.2.3