[Interest] Which thread implementation is best to trigger external library via timers

Mandeep Sandhu mandeepsandhu.chd at gmail.com
Thu Apr 10 10:16:15 CEST 2014


> 1. Subclassing QThread: I've read you should avoid that, so I don't really
> consider it

Not really. Search the archives, where we've had this discussion
numerous times before! :) The conclusion was that there's no 1 right
or wrong way. It has to be taken on a case-by-case basis.

> 2. Move it to thread: networkWorker->moveToThread(thread);
> 3. High level API's: QtConcurrent/QRunning
>
> The requirements are:
> - Run infinite - stop only when requested
> - Needs to run threads event loop
> - Able to call slots via queued events
> and the most critical part
> - direct function calls synchronized via Mutexes from main thread
>
> I've decided to use option 2 but wonder about the following two questions:
> - If I have moved NetworkWorker into its own thread, in which thread is
> QTimer running and can I be sure even when the main thread is overloaded,
> the worker thread still emits and delivers QTimer events?

I think, QTimer will run in whatever thread it's parent is in and
since NetworkWorker will parentless (for moveTothread() to work
properly) it should run in the worker thread. Though you might want to
start it _after_ moving NetworkWorker to the new thread so that timer
events are delivered to it's event loop.

> - There are some methods I still have to call from the main thread, because
> I cannot really connect them via queued signal/slots. E.g. getIP() const or
> getKnownServers() const. So I still need to call it from a place in the main
> thread to get data out of the object:
> QString ip = networkWorker->getIP();
> Is this still safe to use (of course getIP() is synchronized via a mutex) or
> are there any other cleaner solutions?

It should be ok, if the resource access is serialized with a mutex.

I couldn't gather from your explanation as to why you need an event
loop in the thread? There are no signals being emitted by the worker.
If "getIP()" is ok being a direct call, and if there's only the main
thread trying to set values, then I guess even "setIP()" could be a
direct call (serialzed access via mutex ofcourse).

Just my 2 cents.

HTH,
-mandeep



More information about the Interest mailing list