I have a QGraphicsScene with about 1000 QGraphicsItems, which are actually physics items. Each frame they advance, check for collisions, and resolve those collisions, among other things. I would really like to have the physics multithreaded.
It is my understanding that the QGraphics classes are not thread-safe. Meaning, they can only be called from the main thread. Does this force me to send the final item properties (x, y, rotation) each frame to the main thread using a signal/slot mechanism, and then use a main thread method to actually update the QGraphicsItems? Or is there an easier way to do this?
What follows is just a hypothesis: Could I use QtConcurrent to run a method on my list of QGraphicsItems? If I use a QMutex in my QGraphicsItem paint method and a QMutex in my physics method (that will change properties of my QGraphicsItem), would this guarantee that only one thread is reading/writing each QGraphicsItem at any one moment in time?
If I use a QMutex in my QGraphicsItem paint method and a QMutex in my physics method (that will change properties of my QGraphicsItem), would this guarantee that only one thread is reading/writing each QGraphicsItem at any one moment in time?
No, it wouldn't. QGraphicsItem
used heavily while drawing, not only paint
method called. Look, for example, here. Even if it could work, it would be ugly solution, because apparently, QGraphicsItem
can be used not only for painting.
Does this force me to send the final item properties (x, y, rotation) each frame to the main thread using a signal/slot mechanism, and then use a main thread method to actually update the QGraphicsItems? Or is there an easier way to do this?
Yes, you have to move item changing process to main thread. You actually have some alternatives:
QueuedConnection
Don't forget, that you has BlockingQueuedConnection
, if you want to wait for painting finished.
Also, you can use all this stuff with QtConcurent
.
Actually, it is not so difficult to manage. It is much safer and easier, than ensuring thread safety manually.
The bigger problem is that you probably may fail even when trying to read items (using only const
memebers, for example) in worker thread.
As far, as QGraphicsItem
is not thread safe, even reading is not. And my experience of multithread app development in Qt tells me, that if something bad can happen, it will happen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With