[Development] Evolving Qt's multithreading API

André Somers andre at familiesomers.nl
Fri Feb 22 13:06:14 CET 2013


Op 22-2-2013 11:57, Sze Howe Koh schreef:
> On Feb 22, 2013 12:33 AM, "Olivier Goffart" <olivier at woboq.com> wrote:
>> Some more common use case would be (pseudo-code)
>>
>> auto watcher = new QFutureWatcher;
>> QObject::connect(watcher, SIGNAL(finished()), myObject, SLOT(doStuff()));
>> watcher->setFuture(QThrerad::run([]() { return computeStuff(); } ));
>> // who deletes the watcher?
> If the caller creates the watcher, I think it's fine to let the caller
> delete it too. It's an ordinary C++ practice.
I don't really like the need to create a watcher in order to get a 
signal at all, to be honest. Never did.

My own implementation of a task-based system that I recently did, 
involved returning a QSharedPointer<Task> from the task manager. Task 
derives from QObject, and has signals and slots that can be used 
notification. It is similar to QThread, in that it lives in the thread 
that requested the task. It is inspired on QNetworkAccessManager, that 
immediately gives back an instance of a reply that you can either 
directly connect to or ignore.

Using a shared pointer gave me these advantages:
* No need for explicit deletes on either side: the requester can hold on 
to the pointer and use it directly, or use a generic signal from the 
task manager object that also contains a shared pointer to the same 
task. When nobody is interested in the task object any more, it is 
automatically deleted.
* Easily connect to signals like finished() or error() (though it would 
be nice if you could directly connect to a 
QSharedPointer<QObjectDerivedClass> instead of having to use .data() ); 
no need for a separate watcher object
* Value semantics, just like QFuture: a shared pointer is quite cheap to 
pass around

Just like QFuture, it is possible to wait for the task to finish when 
needed.

I'd really like to see such a structure in Qt, as generic as possible. 
Tasks are not only relevant in the context of threads, but also for 
things like network operations and perhaps even I/O operations, 
printing, etc.

André



More information about the Development mailing list