From f89039cbad74f2d7b07145941da06a0b93d18bab Mon Sep 17 00:00:00 2001 From: Sona Kurazyan Date: Wed, 24 Feb 2021 17:17:42 +0100 Subject: [PATCH] Improve docs for QFuture::then() with context MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Be more precise about attaching a continuation with the default (QtFuture::Launch::Sync) launch policy after a continuation with context. Change-Id: I5b80063df2443e5742033864ba012bf34ed4cdf7 Reviewed-by: Ivan Solovev Reviewed-by: Jarek Kobus Reviewed-by: Leena Miettinen Reviewed-by: MÃ¥rten Nordheim (cherry picked from commit 5624b35d6514c5439b9d6dc639dc71228ca7b5ca) Reviewed-by: Qt Cherry-pick Bot --- .../doc/snippets/code/src_corelib_thread_qfuture.cpp | 11 +++++++++++ src/corelib/thread/qfuture.qdoc | 10 ++++++++++ 2 files changed, 21 insertions(+) diff --git a/src/corelib/doc/snippets/code/src_corelib_thread_qfuture.cpp b/src/corelib/doc/snippets/code/src_corelib_thread_qfuture.cpp index a5e1a7f6e4a..a53ca13cc63 100644 --- a/src/corelib/doc/snippets/code/src_corelib_thread_qfuture.cpp +++ b/src/corelib/doc/snippets/code/src_corelib_thread_qfuture.cpp @@ -283,3 +283,14 @@ auto future = QtConcurrent::run([] { // Update UI elements }); //! [19] + +//! [20] +QObject *context = ...; +auto parentFuture = cachedResultsReady ? QtFuture::makeReadyFuture(results) + : QtConcurrent::run([] { /* compute results */}); +auto future = parentFuture.then(context, [] (Results results) { + // Runs in the context's thread +}).then([] { + // May or may not run in the context's thread +}); +//! [20] diff --git a/src/corelib/thread/qfuture.qdoc b/src/corelib/thread/qfuture.qdoc index f74901379f4..b81944200e4 100644 --- a/src/corelib/thread/qfuture.qdoc +++ b/src/corelib/thread/qfuture.qdoc @@ -1174,6 +1174,16 @@ This is because by default \c .then() is invoked from the same thread as the parent. + But note that if the continuation is attached after the parent has already finished, + it will be invoked in the thread where the parent future lives: + + \snippet code/src_corelib_thread_qfuture.cpp 20 + + In the above example if \c cachedResultsReady is \c true, and a ready future is + returned, it is possible that the first \c .then() finishes before the second one + is attached. In this case it will be resolved in the current thread. Therefore, when + in doubt, pass the context explicitly. + \note When calling this method, it should be guaranteed that the \a context stays alive throughout the execution of the chain.