[Interest] Heavily Commented Example: Simple Single Frontend with Two Backends

d3fault d3faultdotxbe at gmail.com
Tue Oct 23 06:50:47 CEST 2012


re: this whole thread

I'm not sure it's fact, but what I've come to... err... believe... is that
while yes, Qt does provide low level primitives for synchronizing threads,
you should not have to use them! Basically if you think you do, you should
instead change your application's design (for those nit pickers out there:
yes there are times when you should -_-... but anyone tackling those cases
won't be benefitting from this email).

An example: instead of guarding access to a list with a qmutex, restrict
access to that list to a single thread and only communicate with it
indirectly using signals and slots. I've found that while you might have to
spend a little bit more time up front designing, your code becomes
remarkably easier to create, understand, and maintain.

Signals and slots have the added advantage of being thread aware... so if
your object is not on a separate thread, the calls are direct and you
aren't wasting time locking a mutex for no reason. Code re-use at it's best.

It's also worth noting Till Oliver's email  (9th) in this thread. If you
aren't doing heavy lifting, you probably don't need a separate thread (also
if you use Qt's async APIs you probably don't either). This can only be
determined on a case by case basis, however.

OT'ish (relative to above): someone mentioned in reply to me that
implementing QThread's run() method is needed for the pure computation use
case. This is simply not true, please stop spreading misinformation. They
clearly did not look at the attached example as I demonstrate the pure
computation case in backend1. I also discuss in the comments of backend1
the infinite loop case... but there are lots of wait to deal with infinite
loops in slots and deciding which way is best will be specific to your use
case (this is a similar topic to deciding if you even need a backend thread
-- that Till Oliver paragraph just above). Your infinite loop in a slot
could call processEvents periodically (if you want to accept events),
ignore them outright, or even have the slot invoke itself (explicitly
specifying Qt::QueuedConnection in invokeMethod) at the end so you can have
an infinite loop that accepts events without ever having to call
processEvents. Deciding which to use can be tough, and I'd stay away from
that last one (slot scheduling itself) unless you're doing a somewhat large
unit of work in every slot invocation/iteration. Example: read an image,
convert it, write it to disk, schedule another. You'd be IO bound so the
threading overhead would be cheap by comparison.

d3fault
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20121022/acdc2d79/attachment.html>


More information about the Interest mailing list