From a40160b8f8930dbe2a0abde4b45e5796264f5782 Mon Sep 17 00:00:00 2001 From: Christian Mollekopf Date: Wed, 1 Apr 2015 01:35:51 +0200 Subject: Added Async::dowhile --- async/autotests/asynctest.cpp | 19 +++++++++++++++++++ async/src/async.h | 29 +++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) (limited to 'async') diff --git a/async/autotests/asynctest.cpp b/async/autotests/asynctest.cpp index 85f5ea5..a387dd6 100644 --- a/async/autotests/asynctest.cpp +++ b/async/autotests/asynctest.cpp @@ -68,6 +68,8 @@ private Q_SLOTS: void testLifetimeWithoutHandle(); void testLifetimeWithHandle(); + void testWhile(); + void benchmarkSyncThenExecutor(); private: @@ -377,6 +379,23 @@ void AsyncTest::testVoidEach() QCOMPARE(check, expected); } +void AsyncTest::testWhile() +{ + + QList processed; + QList list({1, 2, 3, 4}); + auto it = QSharedPointer >::create(list); + Async::dowhile( + [it]() -> bool { return it->hasNext(); }, + [it, &processed](Async::Future future) { + auto value = it->next(); + processed << value; + future.setFinished(); + } + ).exec().waitForFinished(); + QCOMPARE(processed, list); +} + diff --git a/async/src/async.h b/async/src/async.h index 8f6457b..0d1d81e 100644 --- a/async/src/async.h +++ b/async/src/async.h @@ -85,6 +85,7 @@ template using SyncReduceTask = typename detail::identity>::type; using ErrorHandler = std::function; +using Condition = std::function; namespace Private { @@ -226,6 +227,9 @@ template start(); #endif +template +Job dowhile(Condition condition, ThenTask func); + /** * A null job. @@ -507,6 +511,31 @@ Job start() } #endif +static void asyncWhile(const std::function)> &body, const std::function &completionHandler) { + body([body, completionHandler](bool complete) { + if (complete) { + completionHandler(); + } else { + asyncWhile(body, completionHandler); + } + }); +} + } +template +Job dowhile(Condition condition, ThenTask body) +{ + return Async::start([body, condition](Async::Future &future) { + asyncWhile([condition, body](std::function whileCallback) { + Async::start(body).then([whileCallback, condition]() { + whileCallback(!condition()); + }).exec(); + }, + [&future]() { //while complete + future.setFinished(); + }); + }); +} + template Job null() { -- cgit v1.2.3