From 38448b19a1c61cb5d5592e73efdbc4750bb835b2 Mon Sep 17 00:00:00 2001 From: Marc Mutz Date: Wed, 30 Jun 2021 07:17:47 +0200 Subject: QSemaphore: add overload of tryAcquire() ... and C++20 std::counting_semaphore API compatibility. [ChangeLog][QtCore][QSemaphore] tryAcquire() now optionally takes a duration as timeout, not just int milliseconds. [ChangeLog][QtCore][QSemaphore] Added try_acquire{,_for,_until}() for C++20 std::counting_semaphore compatibility. Change-Id: I34b6b4bf57a54745d4b97349903d090c4995338a Reviewed-by: David Faure Reviewed-by: Thiago Macieira Reviewed-by: Qt CI Bot --- .../corelib/thread/qsemaphore/tst_qsemaphore.cpp | 36 +++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) (limited to 'tests/auto/corelib') diff --git a/tests/auto/corelib/thread/qsemaphore/tst_qsemaphore.cpp b/tests/auto/corelib/thread/qsemaphore/tst_qsemaphore.cpp index 9f1512bc44..1d3f3d6776 100644 --- a/tests/auto/corelib/thread/qsemaphore/tst_qsemaphore.cpp +++ b/tests/auto/corelib/thread/qsemaphore/tst_qsemaphore.cpp @@ -32,6 +32,10 @@ #include #include +#include + +using namespace std::chrono_literals; + class tst_QSemaphore : public QObject { Q_OBJECT @@ -47,6 +51,7 @@ private slots: void tryAcquireWithTimeoutForever(); void producerConsumer(); void raii(); + void stdCompat(); }; static QSemaphore *semaphore = nullptr; @@ -500,7 +505,7 @@ public: void run() override; }; -static const int Timeout = 60 * 1000; // 1min +static const auto Timeout = 1min; void Producer::run() { @@ -599,5 +604,34 @@ void tst_QSemaphore::raii() QCOMPARE(sem.available(), 49); } +void tst_QSemaphore::stdCompat() +{ + QSemaphore sem(1); + + auto now = [] { return std::chrono::steady_clock::now(); }; + + QVERIFY(sem.try_acquire()); + QCOMPARE(sem.available(), 0); + QVERIFY(!sem.try_acquire_for(10ms)); + QCOMPARE(sem.available(), 0); + QVERIFY(!sem.try_acquire_until(now() + 10ms)); + QCOMPARE(sem.available(), 0); + + sem.release(2); + + QVERIFY(sem.try_acquire()); + QVERIFY(sem.try_acquire_for(5ms)); + QCOMPARE(sem.available(), 0); + QVERIFY(!sem.try_acquire_until(now() + 5ms)); + QCOMPARE(sem.available(), 0); + + sem.release(3); + + QVERIFY(sem.try_acquire()); + QVERIFY(sem.try_acquire_for(5s)); + QVERIFY(sem.try_acquire_until(now() + 5s)); + QCOMPARE(sem.available(), 0); +} + QTEST_MAIN(tst_QSemaphore) #include "tst_qsemaphore.moc" -- cgit v1.2.3