QThreadFunction Class | Extending Qt Creator Manual
Description: A class template controlling the execution of a function in a separate thread via QtConcurrent::run().

- Extending Qt Creator Manual
- TaskTree
- QThreadFunction
- Extending Qt Creator Manual 19.0.0

# QThreadFunction Class

template <typename ResultType> class QThreadFunction

A class template controlling the execution of a function in a separate thread via QtConcurrent::run(). More...

Header: | `#include <qthreadfunctiontask.h>`

- List of all members, including inherited members

Note: All functions in this class are reentrant.

## Public Functions

| QThreadFunction(QObject *parent = nullptr)
| ~QThreadFunction()
QFuture<ResultType> | future() const
bool | isAutoDelayedSync() const
bool | isDone() const
bool | isResultAvailable() const
ResultType | result() const
ResultType | resultAt(int index) const
QList<ResultType> | results() const
void | setAutoDelayedSync(bool on)
void | setThreadFunctionData(Function &&function, Args &&... args)
void | setThreadPool(QThreadPool *pool)
void | start()
ResultType | takeResult() const
QThreadPool * | threadPool() const

## Signals

void | done(QtTaskTree::DoneResult result)
void | progressRangeChanged(int minimum, int maximum)
void | progressTextChanged(const QString &text)
void | progressValueChanged(int value)
void | resultReadyAt(int index)
void | resultsReadyAt(int beginIndex, int endIndex)
void | started()

## Detailed Description

A QThreadFunction is a convenient class template that combines a stored function to be called later via QtConcurrent::run() with an internal QFutureWatcher monitoring the function execution. Use QThreadFunctionTask to execute the QThreadFunction inside the QTaskTree recipe.

Set a function with its arguments to be executed in a separate thread using setThreadFunctionData() method.

To report an error from inside the function running in a separate thread, place the `QPromise<ResultType> &promise` argument in that function as the first argument, and cancel the promise's future. Example:

     static void copyFile(QPromise<void> &promise, const QString &source,
                          const QString &destination)
     {
         const QFileInfo fi(source);
         if (!fi.exists()) {
             promise.future().cancel(); // The QThreadFunction finishes with DoneResult::Error
             return;
         }

         // Copy file...
     }

     QThreadFunction<void> task;
     task.setThreadFunctionData(copyFile, "source.txt", "dest.txt");
     task.start();

Use setThreadPool() to execute a function in a desired QThreadPool, otherwise the function will use the global thread pool.

Use setAutoDelayedSync() to switch the automatic delayed synchronization.

The function execution can be controlled via started(), done(), resultReadyAt(), progressRangeChanged(), progressValueChanged(), or progressTextChanged() signals. The output data can be collected via result(), resultAt(), or results() getters.

## Member Function Documentation

### `[explicit]` QThreadFunction::QThreadFunction(QObject *parent = nullptr)

Constructs a QThreadFunction with a given parent.

### QThreadFunction::~QThreadFunction()

Destroys the QThreadFunction. If the QThreadFunction is not running, no other actions are performed, otherwise the associated future is canceled, and depending on the automatic delayed synchronization the following actions are performed:

Automatic Delayed Synchronization | Action
--- | ---
On | The associated QFuture is stored in the global registry. Use QThreadFunctionBase::syncAll() on application quit to synchronize all futures stored previously in the global registry.
Off | A blocking call to QFuture::waitForFinished() is executed directly.

When the automatic delayed synchronization is on, the cancellation of the future may be intercepted inside the still running function in a separate thread, so that it may finish as soon as possible without completing its job.

Finally, on application quit, QThreadFunctionBase::syncAll() should be called in order to synchronize all the functions still being potentially running in separate threads. The call to QThreadFunctionBase::syncAll() is blocking in case some functions are still finalizing.

Note: When the automatic delayed synchronization is on, the function will still run for a while after the QThreadFunction's destructor is finished, so it's the user responsibility to ensure that all data the function may operate on is still available. If that can't be guaranteed, set the automatic delayed synchronization to off via QThreadFunction::setAutoDelayedSync(false). In this case the QThreadFunction destructor will blocking wait for the function to be finished before deleting the QThreadFunction. Refer to QCustomTask documentation for more information about `Deleter` template parameter.

See also setAutoDelayedSync() and syncAll().

### `[signal]` void QThreadFunction::done(QtTaskTree::DoneResult result)

This signal is emitted just after the execution of the stored function has finished. The passed result indicates whether the function finished with success or an error.

See also start() and isDone().

### QFuture<ResultType> QThreadFunction::future() const

Returns the QFuture<ResultType> associated with the function executed in a separate thread.

### bool QThreadFunction::isAutoDelayedSync() const

Returns whether the automatic delayed synchronization is on.

See also syncAll() and setAutoDelayedSync().

### bool QThreadFunction::isDone() const

Returns whether the function execution is finished.

See also start() and done().

### bool QThreadFunction::isResultAvailable() const

Returns whether the result is ready.

See also result().

### `[signal]` void QThreadFunction::progressRangeChanged(int minimum, int maximum)

This signal is emitted whenever the progress range of the concurrent call has changed to minimum and maximum.

See also QPromise::setProgressRange() and QFutureWatcher::progressRangeChanged().

### `[signal]` void QThreadFunction::progressTextChanged(const QString &text)

This signal is emitted when the textual progress of the function executed in a separate thread has changed to text.

See also QPromise::setProgressValueAndText() and QFutureWatcher::progressTextChanged().

### `[signal]` void QThreadFunction::progressValueChanged(int value)

This signal is emitted when the progress value of the function executed in a separate thread has changed to value.

See also QPromise::setProgressValue() and QFutureWatcher::progressValueChanged().

### ResultType QThreadFunction::result() const

Returns the ResultType reported by the function executed in a separate thread.

Note: Ensure the result is ready by calling isResultAvailable(), otherwise the call to result() may block in case the result wasn't reported yet, or even crash in case the function execution finished without reporting any result.

See also QFutureWatcher::result().

### ResultType QThreadFunction::resultAt(int index) const

Returns the ResultType reported by the function executed in a separate thread at index.

See also result() and QFutureWatcher::resultAt().

### `[signal]` void QThreadFunction::resultReadyAt(int index)

This signal is emitted whenever the function running in a separate thread reported any partial result at index via QPromise::addResult(). To get the result, call resultAt(index);

See also resultAt() and QFutureWatcher::resultReadyAt().

### QList<ResultType> QThreadFunction::results() const

Returns the list of ResultType reported by the function executed in a separate thread.

See also result(), resultAt(), and QFuture::results().

### `[signal]` void QThreadFunction::resultsReadyAt(int beginIndex, int endIndex)

This signal is emitted whenever the function running in a separate thread reported any ready results indexed from beginIndex to endIndex. To get the result, call resultAt(index);

See also resultAt() and QFutureWatcher::resultsReadyAt().

### void QThreadFunction::setAutoDelayedSync(bool on)

Sets the automatic delayed synchronization to on.

By default, an automatic delayed synchronization is on, meaning the destruction of the running QThreadFunction object won't blocking wait until the function running in separate thread is finished. Instead, the associated QFuture is canceled, and the function is left running until it's finished. The cancellation can be intercepted by the function running in a separate thread via the QPromise argument, so that it may finish early without completing its job. In case the automatic delayed synchronization is on, it's necessary to call QThreadFunctionBase::syncAll() on application quit, in order to synchronize all the possibly running functions in separate threads.

When the automatic delayed synchronization is off, the synchronization happens on QThreadFunction's destruction, what can block the caller thread for considerable amount of time.

The automatic synchronization is used only when QThreadFunction was executed from the main thread.

See also syncAll() and isAutoDelayedSync().

### template <typename Function, typename... Args> void QThreadFunction::setThreadFunctionData(Function &&function, Args &&... args)

Sets the function to be executed with passed args in a separate thread when start() is called.

See also QtConcurrent::run().

### void QThreadFunction::setThreadPool(QThreadPool *pool)

Sets the QThreadPool pool to be used when executing the call. If the passed pool is `nullptr`, the QThreadPool::globalInstance() is used.

See also threadPool().

### void QThreadFunction::start()

Starts the asynchronous invocation of stored function in a separate thread. Connect to done() signal to collect the result reported by the function.

See also setThreadFunctionData() and done().

### `[signal]` void QThreadFunction::started()

This signal is emitted just after the execution of the stored function has started.

See also done().

### ResultType QThreadFunction::takeResult() const

Takes (moves) the ResultType reported by the function executed in a separate thread.

Note: Ensure the result is ready by calling isResultAvailable(), otherwise the call to takeResult() may block in case the result wasn't reported yet, or even crash in case the function execution finished without reporting any result.

See also QFuture::takeResult().

### QThreadPool *QThreadFunction::threadPool() const

Returns the thread pool that is used when executing the call. If `nullptr` is returned, the QThreadPool::globalInstance() is used.

See also setThreadPool().