[Development] Evolving Qt's multithreading API

Sze Howe Koh szehowe.koh at gmail.com
Wed Feb 20 18:03:06 CET 2013


On 20 February 2013 23:57, Olivier Goffart <olivier at woboq.com> wrote:
> Someone has already been working of some feature such as:
...
https://codereview.qt-project.org/#/t/65/

Ah, these are quite similar to my second post
(http://lists.qt-project.org/pipermail/development/2013-February/009970.html).
Some comments:


> static QThread::run(QRunable*)
> static QThread::run(Function)

- We already have (protected) void QThread::run(), which is the core
of all Qt threads. Thus, the new (public static) methods shouldn't be
called 'run()'.
- QThread is a thread control interface. I think it's preferable for
the new (public static) methods to return a QThread pointer, so that
the programmer can interact with the new thread.


> static QThreadPool::run(Function)

- We already have (public) void QThreadPool::start(QRunnable*) and
(public) bool QThreadPool::tryStart(QRunnable* runnable, int priority
= 0). The new function-based method should mirror start() and
tryStart()
- We need to specify the thread pool to use (the global one, or a
custom one), so this can't be static


To recap, here are my proposed methods:
1) static QThread* QThread::setupSimpleThread(QRunnable *runnable);
2) static QThread* QThread::setupSimpleThread(Function func, Args arg, ...);
3) static QThread* QThread::setupEventLoop(QObject* worker);
4) void QThreadPool::start(Function func, Args arg, ...);
5) bool QThreadPool::tryStart(Function func, Args arg...);


I suggested (1, 2, 3) because Qt currently recommends two ways of using QThread:
i) (Without event loop) Subclass QThread, reimplement QThread::run(),
instantiate the derived QThread
ii) (With event loop) Subclass and instantiate a worker QObject,
instantiate a basic QThread, and call moveToThread()

These two approaches to using QThread look completely different, and
the code isn't clear on whether an event loop is involved or not.
Moving forward,
- (1, 2, 3) provides the same "feel" for starting a new low-level
thread, regardless of whether an event loop is involved or not
- (1, 2, 3) makes it clear if an event loop is involved or not
- (1) can replace (i) in most cases -- the effort required by the
programmer is exactly the same (unless they want their new thread to
emit signals)
- (3) can replace (ii) in all cases -- it even results in slightly shorter code


There are still some wrinkles to iron out though:
- (4) is slightly inconsistent with its existing counterpart 'void
QThreadPool::start(QRunnable* runnable, int priority = 0)'... any
suggestions?
- Should (3) accept an arbitrary number of QObjects?


> Remember also that C++11 contains already a some set of threading primitive
> such as std::thread,  std::async, std::future

Yes, although it's good to polish what we already have :)


Regards,
Sze-Howe



More information about the Development mailing list