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

Oliver.Knoll at comit.ch Oliver.Knoll at comit.ch
Wed Dec 24 10:22:59 CET 2008


Knoll Oliver, ITS-CMT-SUI-RM-IFB wrote on Wednesday, December 24, 2008 9:54 AM:

> ..
> // in GUI thread: slot
> void MyWidget::handleDataReady(QImage image) {
>    // the "image" is already a copy of the computedImage
>    m_imageToBePainted = image;

Uhm, I didn't actually finish my example (because it is wrong anyway ;), so just for the record:

class MyWidget : public QWidget {
  Q_OBJECT
  ...
private slots:
   // connected to the "queued signal" from the worker thread
  void handleDataReady(QImage image);
private:
  QImage m_imageToBePainted;

void MyWidget::handleDataReady(QImage image) {
   // the "image" is already a copy of the computedImage, so it is "safe"
   // to use it (but see my previous post!)

   // store the image for later painting
   m_imageToBePainted = image;
   // trigger a repaint
   this->update();
}

void MyWidget::void paintEvent(QPaintEvent *event) {
  QPainter p(this);
  ...
  p.drawImage(m_imageToBePainted, ...);
  ...
}

And just now I realised that the above solution probably *is* thread-safe, as Andreas suggested! :) (But still, the copy should be done within the worker thread, that is, before emitting the signal. Not in the GUI thread at which point the image could already have been changed).

Because assuming that the worker thread would indeed go on and happily modify the m_computedImage (which uses shared data with with m_imageToBePainted up to this point) the actual data gets "detached" and we indeed have two separate copies then :)

Oh, and here we go: http://doc.trolltech.com/4.4/threads.html#threads-and-implicit-sharing

"Beginning with Qt 4, implicit shared classes can safely be copied across threads, like any other value classes. They are fully reentrant. The implicit sharing is really implicit.

In many people's minds, implicit sharing and multithreading are incompatible concepts, because of the way the reference counting is typically done. Qt, however, uses atomic reference counting to ensure the integrity of the shared data, avoiding potential corruption of the reference counter."

:)


Happy (thread-safe) Xmas: protect the "critical section" (the presents under the Xmas tree), or else you'll have a "race condition" (your children running towards the Xmas tree ;). And don't get into a dead-lock during the Xmas dinner: do it the way the Dining Philosophers do ;)

Cheers, Oliver
--
Oliver Knoll
Dipl. Informatik-Ing. ETH
COMIT AG - ++41 79 520 95 22




More information about the Qt-interest-old mailing list