[Qt-interest] Qt4.4.3 paintEvent thread-safe

Thiago Macieira thiago.macieira at trolltech.com
Wed Dec 24 12:02:13 CET 2008


Oliver.Knoll at comit.ch wrote:
>   // make a copy of the computed image and pass this copy to the
>   // GUI thread - but ATTENTION: IMPLICIT SHARING (see below)
>   QImage copiedImage = m_computedImage;
>   emit dataReady(copiedImage);
>}

>> image. This way there's no concurrent access to the image data
>> between the two threads.
>
>But even the above code is probably IMO not thread-safe! Because QImage
> - as many other Qt classes such as QString - use "implicit sharing"!
>
>  http://doc.trolltech.com/4.4/shared.html#list-of-classes
>
>That means that merely doing a
>
>  QImage copiedImage = m_computedImage;
>
>does not copy the actual pixel data (yet - only as soon as the
> "copiedImage" is actually modified later on). And this IMHO means that
> simply "copying" a QImage (or any other implicitly shared data
> structure) like this does not prevent concurrent access to the pixel
> data between two threads - unless you "force" a complete copy in some
> way! Or you really protect the "critical section" (the shared data)
> with semaphores.

Hi Oliver

The above code is *supposed* to work just fine. The Qt classes that do 
implicit sharing also do atomic copy-on-write detaching. That's all 
supposed to be thread-safe. You shouldn't notice any difference between a 
deep-copy "int" and a shallow-copy QImage or QList.

The signal function will call QMetaObject::activate, which is responsible 
for going through the QConnectionList associated with that signal and 
activate the slots. When it encounters a QueuedConnection or if the target 
object in an AutoConnection is in a different thread, it will do a copy of 
the arguments, just like you did at the top of this message. So that copy 
is unnecessary.

The shallow-copies will simply increase the reference count of the 
objects. When your thread or the target threads calls any non-const 
function in the object, the atomic detaching will trigger and will cause a 
safe separation between the two objects.

Now, that's how it's supposed to work. If you have an example of this not 
working, let us know. It might be a bug somewhere in Qt we have to fix (it 
might be even a heisenbug).

-- 
Thiago Macieira - thiago.macieira (AT) nokia.com
  Senior Software Engineer - Nokia, Qt Software
  Qt Software is hiring - ask me
      Sandakerveien 116, NO-0402 Oslo, Norway
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: This is a digitally signed message part.
Url : http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20081224/d4d83d9e/attachment.bin 


More information about the Qt-interest-old mailing list