Daily Archives: 10.01.2018

Link

If you are using Qt and you need to run some code in a separate thread, chances are that you are using QThread for the job. QThread is a very old class in Qt, making its first appearance in Qt 2.2, released on the 22nd of September 2000. Its responsibility is to start a new thread, and let you execute code in that thread.

There are two main ways of running code in a separate thread using QThread:

  1. subclassing QThread and overriding run();
  2. creating a “worker object” (some QObject subclass) and connecting it to QThread signals.

Please refer to my Qt World Summit 2017 presentation (video) for more details about how to use these two functions. There are also lots of other documentation and blog posts available on the internet, discussing the pros and the cons of the two approaches.

Enter QThread::create()

In Qt 5.10 I have added another way to run some code in a new thread. Inspired by C++11’s std::thread, I have introduced QThread::create, a factory function that creates a new QThread which will run a user-provided callable:

[sourcecode lang=”cpp”]
QThread *thread = QThread::create([]{ runSlowCode(); });
thread->start();
[/sourcecode]

The advantage of this approach is that it avoids creating a new QThread subclass manually for the sole purpose to override its run() member function and run some code.

Unlike std::thread, however, the newly-created thread is not automatically launched; the user is expected to start it with an explicit call to start(). This allows users to do some extra work before starting the thread, for instance, connect to its signals, set the name of the thread, or change its priority, as demonstrated by this snippet:

[sourcecode lang=”cpp”]
QThread *thread = QThread::create(myFunction);

thread->setObjectName(“WorkerThread”); // name to appear in ps, task manager, etc.
connect(thread, &QThread::started, gui, &Gui::threadHasStarted);

thread->start();
[/sourcecode]

The user acquires ownership of the newly-created QThread object.

With a C++17 capable compiler it is also possible to pass extra arguments to QThread::create(): these arguments will be then passed to the function in the new thread, using the same semantics as std::thread‘s constructor. For instance:

[sourcecode lang=”cpp”]
QThread *thread = QThread::create(myFunction, arg1, arg2);
// extra setup…
thread->start(); // calls myFunction in another thread, passing arg1 and arg2
[/sourcecode]

That’s it! I hope this will be useful to you. However, the API of QThread::create() is only half of the story. If you want to know more about what this apparently little patch meant for Qt, keep reading.

Implementation notes

In afterthought, the implementation of QThread::create is very simple. However, when doing the necessary research, I found a small …read more

Source:: https://www.kdab.com/new-qt-5-10-qthreadcreate/