Qt Multithreading overview

  1. What this wiki about 
  2. APIs for using multithreading in Qt 
  3. QThread 
  4. Links 

What this wiki about

Here will be just some basic info about using threads in Qt

APIs for using multithreading in Qt

There are three ways of using threads in Qt:

  • QThread
  • QRunnable
  • QtConcurrent

Main differences you could see in this table:

caption

1 Excluding QtConcurrent::run, which realised with QRunnable so takes all its pros and cons.

QThread

The main difference lies in the possibility to use eventloop.
It means that you could safely use signals and slots among different threads!
Also good thing is to start thread with different priority – for example if you need background non-priority process.

But it has one thing which you should remember – the object of thread lives in the SAME thread where it was constracted, while it’s RUN method executes in new thread.
Thus QThread object not realy a separate thread – it’s in some way a controller over new thread.

Let’s show this on example:

TestThread::TestThread(QObject *parent) :
    QThread(parent)
{
    m_object = new QObject(this);
}

void TestThread::run()
{
    QObject * thread_object = new QObject(0);

    qDebug() << "Object which constracted in TestThread constructor:" <<  m_object->thread();
    qDebug() << "Object which constracted in TestThread run method:" << thread_object->thread();
    exec();
}

Where m_object is TestThread private variable.

In terminal you will see this:

Object which constracted in TestThread constructor: QThread(0x10fb750) 
Object which constracted in TestThread run method: TestThread(0x1188da0)

So if you want to do some thing in separate thread you must declare them only in run method!

Example project could be downloaded from attached files

Links

http://developer.qt.nokia.com/wiki/Threads_Events_QObjects_Russian#c85a2132c6f1c23012897ca6f0255fb6

ShareShare on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on VKEmail this to someone