[Qt-interest] efficient Wait for Thread finished?

Arnold Krille arnold at arnoldarts.de
Tue Jan 20 21:27:17 CET 2009


On Tuesday 20 January 2009 21:06:53 you wrote:
> Arnold Krille schrieb:
> > That is all described pretty well in the Qt docs, I got most of my multi-
> > thread knowledge from there (and from actually using it). :-)
> I have never worked with thread locking and although have read the
> QMutex Doc page multiple times am not sure
> if I got it right.
> If I have inside a function this here:
>     QMutex mutex;
>     QMutexLocker locker(&mutex);
> the any other function will not be affected because locking only happens
> if in other functions the code execution comes along a
> mutex.lock() which finds out that excatly this is already locked and
> waits until this is unlocked. In the case of above locking will
> then never happen because the mutex object is unknown outside of the
> function.

That is correct.

> If I put the
>     QMutex mutex;
> in the class definition, then I use the same mutex everywhere in all
> functions and locking is possible, but still any function not having a
> mutex.lock() will still be executed.

That is correct to.

Think: "Protect the data-structure by a mutex." The data-structure is 
accessible within the class, so the mutex has to be accessible in the class 
too. And you should make both private (or maybe protected) so no one tries to 
access the data-structure from the outside without thinking about the mutex.

> Contrary to this, what I had been thinking first was that if I have any
> mutex in a thread derived class that would block any attempt to access
> members or functions in the class and cause a wait for the class to be
> unlocked.

No, you can even have any number of mutexes in a class (it doesn't even have 
to derive from QThread!). But if you need lots of mutexes, you should probably 
look at QSemaphore instead. There is even an example in the Qt docs about 
doing a fifo buffer (aka ring-buffer) with two semaphores. (And also examples of 
the same with mutexes and read-write-locks.)

Have fun,

Arnold
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 197 bytes
Desc: This is a digitally signed message part.
Url : http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20090120/c76f78c1/attachment.bin 


More information about the Qt-interest-old mailing list