diff options
author | Allan Sandfeld Jensen <allan.jensen@qt.io> | 2017-04-12 17:34:41 +0200 |
---|---|---|
committer | Allan Sandfeld Jensen <allan.jensen@qt.io> | 2017-07-02 20:08:36 +0000 |
commit | eaee1209f0ead5be786e81db8aee604ccfea85b0 (patch) | |
tree | 3292857a49ef8e3efa2a2213754bbbd49a808a4a /src/corelib/thread/qsemaphore.cpp | |
parent | ab2c1f9509c76d61773ad0df3eaeb0ea1c2bbddf (diff) |
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 <thiago.macieira@intel.com>
Diffstat (limited to 'src/corelib/thread/qsemaphore.cpp')
-rw-r--r-- | src/corelib/thread/qsemaphore.cpp | 25 |
1 files changed, 12 insertions, 13 deletions
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; |