PDA

View Full Version : Multi threading ...



kiranraj
18th June 2007, 15:14
Hi ,

I have a problem with freezing the display....

Problem is similar to this model.

step 1. I need to create and display thousands of rectangles. ( QGraphicsItem)
step 2. Do some calculation and Create lines ( by default hidden ) b/w the rectangles. ( millions of lines)
Here lines and rects are QGraphicsItems

Creation and display of rectangles is fast but creation of lines is taking too much time.

So iam planning to multithread the application, by executing the creation of lines in seperate thread to prevent freezing the display.

After displaying the Rectangles. The user should be able to do Zoom In, Zoomout, Panning.
While the background thread is ceating the lines.

My problem is ....
1. Is it possible to do this ? since Both the threads will be accessing the same GraphicsScene.
Main thread will be reading other thread will be adding line items to it.
2. Is there any way to synchronize both the threads ?
3. Is there any other solution?

Thanks...

^NyAw^
18th June 2007, 16:26
Hi,

The working thread can't draw directly to the screen. Every time it has a calculated line, it have to emit it to the main thread and the main thread has to display the line.

Take a look at "mandelbrot" example. It has a worker thread that render(calculate) an image and send it to the main thread that will display it.

wysota
18th June 2007, 16:51
1. Is it possible to do this ?
Yes.

since Both the threads will be accessing the same GraphicsScene.
Use signals and slots - do all needed calculations in the worker thread and then signal the results to the main thread that will insert the new item into the scene.

Main thread will be reading other thread will be adding line items to it.
No, items have to be added by the main thread. If you don't need any calculations and just want to add a bunch of items without freezing the application then you won't need another thread - just use a timer with a 0 timeout.

2. Is there any way to synchronize both the threads ?
Signals and slots or events (which is practically the same).

3. Is there any other solution?
I think I already answered that... But anyway a small snippet of code to illustrate:

class GraphicsScene : public QGraphicsScene {
Q_OBJECT
public:
GraphicsScene(...) : QGraphicsScene(...){
m_last = -1;
initializeScene(); // starts the asynchronous task that fills the scene with items
}
private slots:
void initializeScene(){
int done = 0;
while(++m_last<10000 && done++<10){
addLine(...);
}
if(m_last>=10000)
return;
QTimer::singleShot(0, this, SLOT(initializeScene()));
}
};