From 3b8ebe6d4235f5ba12bc9c9854a6dd28cbff06b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dan=20Vr=C3=A1til?= Date: Sat, 21 Feb 2015 12:11:42 +0100 Subject: Async: allow appending Jobs to already running or finished Jobs When user gets a Job (from a method call for instance), which is already running or might have even finished already, they can still append a new Job to the chain and re-execute it. The Job will internally chain up to the last finished Job, use it's result and continue from the next Job in the chain. If a Job in the chain is still running, it will wait for it to finish and pass the result to the next Job in the chain. --- async/autotests/asynctest.cpp | 72 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) (limited to 'async/autotests') diff --git a/async/autotests/asynctest.cpp b/async/autotests/asynctest.cpp index 73026bb..7437608 100644 --- a/async/autotests/asynctest.cpp +++ b/async/autotests/asynctest.cpp @@ -59,6 +59,10 @@ private Q_SLOTS: void testErrorHandler(); + + void testChainingRunningJob(); + void testChainingFinishedJob(); + void benchmarkSyncThenExecutor(); private: @@ -399,6 +403,74 @@ void AsyncTest::testErrorHandler() +void AsyncTest::testChainingRunningJob() +{ + int check = 0; + + auto job = Async::start( + [&check](Async::Future &future) { + QTimer *timer = new QTimer(); + QObject::connect(timer, &QTimer::timeout, + [&future, &check]() { + ++check; + future.setValue(42); + future.setFinished(); + }); + QObject::connect(timer, &QTimer::timeout, + timer, &QObject::deleteLater); + timer->setSingleShot(true); + timer->start(500); + }); + + auto future1 = job.exec(); + QTest::qWait(200); + + auto job2 = job.then( + [&check](int in) -> int { + ++check; + return in * 2; + }); + + auto future2 = job2.exec(); + QVERIFY(!future1.isFinished()); + future2.waitForFinished(); + + QCOMPARE(check, 2); + QVERIFY(future1.isFinished()); + QVERIFY(future2.isFinished()); + QCOMPARE(future1.value(), 42); + QCOMPARE(future2.value(), 84); +} + +void AsyncTest::testChainingFinishedJob() +{ + int check = 0; + + auto job = Async::start( + [&check]() -> int { + ++check; + return 42; + }); + + auto future1 = job.exec(); + QVERIFY(future1.isFinished()); + + auto job2 = job.then( + [&check](int in) -> int { + ++check; + return in * 2; + }); + + auto future2 = job2.exec(); + QVERIFY(future2.isFinished()); + + QCOMPARE(check, 2); + QCOMPARE(future1.value(), 42); + QCOMPARE(future2.value(), 84); +} + + + void AsyncTest::benchmarkSyncThenExecutor() -- cgit v1.2.3