[Development] Execute a function in the specified existing thread

Volker Hilsheimer volker.hilsheimer at qt.io
Thu Jun 8 12:49:07 CEST 2023



> On 7 Jun 2023, at 17:20, Thiago Macieira <thiago.macieira at intel.com> wrote:
> 
> On Wednesday, 7 June 2023 01:53:47 PDT JiDe Zhang wrote:
>> I am writing a tool to allowed call a function in the specified existing
>> thread, I want to contribution it to Qt project, are you like?
> 
> We do this internally, but don't usually expose it. If you're going to 
> contribute it, please make sure your contribution uses QMetaCallEvent.
> 
> Anyway, the important question is whether you have the QThread for that thread 
> or an object that lives in that thread. If you have the latter, it's already 
> easy to do so:
> 
>  QMetaObject::invokeMethod(obj, Qt::QueuedConnection, [] { doSomething(); });


Fabian had the idea of injecting an event into a thread’s event queue, without needing a receiver object to post the event to:

https://codereview.qt-project.org/c/qt/qtbase/+/470488

This came out of the recent improvements to e.g. QTimer::singleShot event and QCoreApplication::requestPermission, where we have to create a receiver object  just so that we can post the QMetaCallEvent to the correct event queue. By allowing metacall events in the queue without receiver, we could remove that overhead.

With such a mechanism we could easily implement a “run callable in thread” (or "in thread of given object") API without creating the kind of “Caller” object your implementation has. To supporting the various callables we can use in connections or callback-APIs, the changes we recent made to qobjectdefs_impl.h, esp QtPrivate::QCallableObject and QtPrivate::makeCallableObject) should give us the higher-level building blocks.

Volker



More information about the Development mailing list