Support Threading on all (even imported) QObjects #1155
Labels
🤔 discussion
Feedback welcome
⬆️ feature
New feature or request
👷 refactor
Something needs to change
In a recent discussion with @milianw , he come up with an interesting idea to extend support for cxx_qt::Threading to all QObjects, even imported ones.
Current Implementation
Currently we use
CxxQtGuardedPointer
as a thread-safe version ofQPointer
, which however requires the QObject to be aware of the GuardedPointer, so it only works with our own QObjects.New Idea
We could get around this requirement by creating a "context" object, which is manually memory-managed and is basically only responsible for keeping a handle to the thread on which the original QObject lives.
Example by @milianw :
Note: The memory-management of
context
will look different in our case, as we either need to create a context object per CxxQtThread, or perqueue
call.Note that if we delete the context object in the destructor of CxxQtThread this would potentially delete it too early, as the invokeMethod may not yet have finished.
Implications
Note however, that this expects the
context
and the original QObject to remain on the same thread!Which means either the threading itself, or
moveToThread
must beunsafe
.Currently QObjects don't implement
Send
, which is a bit at odds withmoveToThread
, which does indeed allow moving QObjects between threads.So it's likely that
moveToThread
would have to beunsafe
either way, which would be one way to remedy this conundrum.If it's
unsafe
to callmoveToThread
, we can ask callers to guarantee that noQtThread
instance for this QObject currently exists.moveToThread
also emits aQEvent::ThreadChange
, which we could catch via an event filter.https://doc.qt.io/qt-6/qobject.html#moveToThread
So another option would be to change the contexts thread at the same time.
However, the thread safety implications of this are also questionable.
The text was updated successfully, but these errors were encountered: