Skip to content

QThread

ModuleCore
Include
#include <QCoroThread>
CMake
target_link_libraries(myapp QCoro::Core)
QMake
QT += QCoroCore

QThread has two events: started and finished. QCoro provides a coroutine-friendly wrapper for QThread - QCoroThread, which allows co_awaiting those events.

To wrap a QThread object into the QCoroThread wrapper, use qCoro():

QCoroThread qCoro(QThread &);
QCoroThread qCoro(QThread *);

waitForStarted()

Waits for the thread to start. Returns true if the thread is already running or when the thread starts within the specified timeout. If the thread has already finished or fails to start within the specified timeout, the coroutine will return false.

If the timeout is set to -1, the operation will never time out.

See documentation for QThread::started() for details.

QCoro::Task<bool> QCoroThread::waitForStarted(std::chrono::milliseconds timeout);

waitForFinished()

Waits for the Waits for the process to finish or until it times out. Returns bool indicating whether the process has finished successfuly (true) or timed out (false). thread to finish. Returns true if the thread has already finished or if it finishes within the specified timeout. If the thread has not started yet or fails to stop within the specified timeout the coroutine will return false.

If the timeout is set to -1, the operation will never time out.

See documentation for QThread::finished() for details.

QCoro::Task<bool> QCoroThread::waitForFinished(std::chrono::milliseconds timeout);

QCoro::moveToThread()

A helper coroutine that allows changing the thread context in which the coroutine code is currently being executed.

When co_awaited, the current coroutine will be suspended on the current thread and immediately resumed again, but in the context of the thread that was passed in as an argument.

QCoro::Task<> QCoro::moveToThread(QThread *thread);

Examples

#include <QCoroThread>
#include <QThread>

#include <memory>

QCoro::Task<void> MainWindow::processData(const QVector<qint64> &data) {
    std::unique_ptr<QThread> thread(QThread::create([data]() {
        // Perform some intesive calculation
    }));
    thread->start();

    ui->setState(tr("Processing is starting..."));
    co_await qCoro(thread.get()).waitForStarted();
    ui->setState(tr("Processing data..."));
    co_await qCoro(thread.get()).waitForFinished();
    ui->setState(tr("Processing done."));
}