Contact

If you like a new Web or Desktop
application, update a existing one
or add new modifications. Your at
the right place and hit the
hire me button

Follow

If your intersted you can follow
me on Twitter by clicking here

Web and Apps Building Refernce World Wild Web UNIX Apps AND Tips Programming languages

Threads

I was very politely asked to write a chapter that would illustrate basic use of threads in Qt4, so here it is. Greetings to azark :-]

The purpose of this tutorial is to show how to run some computations in new thread (in order not to block main window). We'll change our My first Qt GUI application.

New user interface:

Let's implement mythread.h and mythread.cpp

mythread.h - subclass of QThread

#ifndef MYTHREAD_H
#define MYTHREAD_H

#include <QtGui>

class MyThread : public QThread
{
Q_OBJECT

public:
MyThread(QObject *parent);
void run(); // this is virtual method, we must implement it in our subclass of QThread
};


#endif

mythread.cpp

#include "mythread.h"

MyThread::MyThread(QObject *parent)
:
QThread(parent)
{
}

void MyThread::run()
{
qDebug() << "Executing in new independant thread, GUI is NOT blocked";

for(int i=0;i<10;i++)
{
qDebug() << "Time: " << 10-i;

int t=1;

// some OS specific stuff
// mingw (3.4.2) sleep on windows is called _sleep and uses microseconds
#ifdef Q_OS_WIN32
t = t * 1000;
_sleep(t);
#else
sleep(t);
#endif

}

qDebug() << "Execution done";

exec();
}

App in action:

Download complete project my_first_qt_app-threaded.zip and try.

Things to notice about threads

Bear in mind that two or more threads cannot simultaneously access one device/widget during a write operation. If you lanuch 2 threads and each will write to, for instance textEdit, your application will crash. Some locking mechanism (mutex, semaphore, wait condition) must be used to handle access in a non-conflicting way. If you just need read access, it's OK from as many threads as you want.

Now read QThread, I hope you'll understand it better after reading this.

Ideas how to improve this tutorial are welcome.