[Qt-interest] Qt4.4.3 paintEvent thread-safe
Oliver.Knoll at comit.ch
Oliver.Knoll at comit.ch
Wed Dec 24 09:54:10 CET 2008
Andreas Pakulat wrote on Tuesday, December 23, 2008 11:43 AM:
> > ...
> Whatever method you use to signal the Qt-painting-thread to update
> needs to carry the image as parameter. The receiving method stores it
> in a local variable and then when paintEvent is called it can use the
Uh oh, I would be careful with this approach! First off, I think it should be the "worker thread" (the thread which "owns" the object) which should be responsible to produce a copy (which is then passed as parameter to the signal), not the slot: as soon as the slot code is being executed the "worker thread" is already running again and possibly modifying the image data just at the very moment when you try to do a copy!
So better:
// in worker thread:
void WorkerThread::compute() {
// calculate the image, using a QPainter or whatever
m_computedImage = ...;
...
// 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);
}
// in GUI thread: slot
void MyWidget::handleDataReady(QImage image) {
// the "image" is already a copy of the computedImage
m_imageToBePainted = image;
> 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.
Cheers, Oliver
--
Oliver Knoll
Dipl. Informatik-Ing. ETH
COMIT AG - ++41 79 520 95 22
More information about the Qt-interest-old
mailing list