PDA

View Full Version : a design problem in multithread programming



ryen
4th April 2009, 08:46
Hi, I am using Qt4.5 to write a render program. Since the rendering is time-consuming, I create a thread to do it. Now my program's structure is like this. The generated pixels is store in a vector, and there is a QTimer in the rendering thread, so after a few millionseconds,the rendering thread can pass the newly generated pixels through a Signal. But when I run the programm,there always throw some memory excpetions, e.g Heap corruption.:(
I think I should do a mutex lock somewhere,but after some experiments, the problem always existing.
I think my design is poor, is there any other design can do this job in Qt?
(Sorry for my poor English.)

faldzip
4th April 2009, 09:23
It looks like producer-consumer problem (http://en.wikipedia.org/wiki/Producer-consumer_problem).
You need to get access to the vector for both threads and lock them with mutex on write/read operations. Also if you have something like shared index number (first free slot in vector) you need to lock it before reading it and locking vector and unlock after updating it and unlocking vector. Then you can use signal/slot to notify the consumer thread that new data arrived to vector.

talk2amulya
4th April 2009, 09:57
would you mind sharing the relevant code?

ryen
4th April 2009, 14:19
Thanks for your attention! I've read the Mandelbrot example which is just fit my problem. And the rendering thread pass a QImage object instead of a vector to the GUI thread. I followed this and solved my problem. It seems that it is more difficult to manage the vector.
Now I have a little problem. below is my rendering thread's run method.

void MyThread::run()
{
render(); // is this unblock?
exec();
}

Because I have a QTimer,so I need to add the "exec()" at the bottom. but if the "render()" fuction is executed in block-mode. How can the rendering thread start its own event-loop when the render fuction is being executed? (But now ,it just works, the readering thread can receive the Timer's timeout signals,and then pass the QImage to the GUI thread!)

talk2amulya
4th April 2009, 14:46
everywhere in Qt where u see an exec() being used, its actually of the class QEventLoop..all classes, be it QDialog, QThread or QCoreApplication uses the exec of QEventloop internally..now what exec does is it ONLY processes the events that are posted/sent to the ur thread/main thread/dialog..so in ur render(), certain events are posted and they are executed when exec is called..event loop is started when u created the thread itself..when exec is called, those events are processed.