Pages

Basic multithreading with Qt

Qt provides a class, QThread, that helps us creating multithreading applications. The basic idea is that you create a your own class derived from QThread, implement its run() method to do what you expect it doing and then use it instantiating an object of that class for each thread you want to be available, and explicitely starting it.

As an example, think to a writer class that simply outputs a few times a string:
#ifndef WRITER_H
#define WRITER_H

#include <QThread>
#include <QString>

class Writer : public QThread
{
public:
explicit Writer(const QString& mark) : mark_(mark) {}

void run();
private:
QString mark_;
};

#endif // WRITER_H

As said, we redefine run(), virtual QThread function to let it performs a specific task:
void Writer::run()
{
for(int i = 0; i < 20; ++i)
{
std::cout << qPrintable(mark_);
msleep(200);
}
}

The QThread::msleep() function is used to put the current thread to sleep for the passed millisecs.

Here is the main function for this first approach to Qt multithreading:
#include <QtCore/QCoreApplication>
#include <QTimer>
#include "writer.h"

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv); // 1.

Writer w1("One");
Writer w2("Two");
Writer w3("Three"); // 2.

w1.start();
w2.start();
w3.start(); // 3.

w1.wait();
w2.wait();
w3.wait(); // 4.

QTimer::singleShot(12000, &a, SLOT(quit())); // 5.

return a.exec();
}

1. To keep the code as simple as possible, I choose a Qt console application as target.
2. Three objects of the customized QThread subclass have been created.
3. And started. Once started, a thread is on its own till its run() method terminates.
4. We wait till all three sub-threads complete their job.
5. Then we send an event to the application loop, for asking to terminate in a dozen of seconds.

2 comments: