Qt 4.8: Starting Threads with QThread

Qt Reference Documentation

- Qt 4.8
- ALL VERSIONS

- A
- A
- A
- Print

Synchronizing Threads

# Starting Threads with QThread

A QThread instance represents a thread and provides the means to start() a thread, which will then execute the reimplementation of QThread::run(). The `run()` implementation is for a thread what the `main()` entry point is for the application. All code executed in a call stack that starts in the `run()` function is executed by the new thread, and the thread finishes when the function returns. QThread emits signals to indicate that the thread started or finished executing.

## Creating a Thread

To create a thread, subclass QThread and reimplement its run() function. For example:

     class MyThread : public QThread
     {
         Q_OBJECT

     protected:
         void run();
     };

     void MyThread::run()
     {
         ...
     }

## Starting a Thread

Then, create an instance of the thread object and call QThread::start(). Note that you must create the QApplication (or QCoreApplication) object before you can create a QThread.

The function will return immediately and the main thread will continue. The code that appears in the run() reimplementation will then be executed in a separate thread.

Creating threads is explained in more detail in the QThread documentation.

Note that QCoreApplication::exec() must always be called from the main thread (the thread that executes `main()`), not from a QThread. In GUI applications, the main thread is also called the GUI thread because it's the only thread that is allowed to perform GUI-related operations.

Synchronizing Threads