View Full Version : basic qthread question

9th September 2008, 17:17
hi, there
By clicking a button, I want to do heavy calculation several times in a loop and don't want them block the performance of the GUI, here is what I did. Although it did not block the GUI, it block the loop. How can I do it correct?

Somewhere in the GUI I have

for (int i = 1; i < 10; i++){
cout<<"# "<<i<<endl;
TrashThread trash(this, i);

For the TrashThread class, I have

TrashThread::TrashThread(QObject *parent, int i) : QThread(parent)
cout<<"thread "<<i<<endl;

void TrashThread::run()

cout<<"sleep 5sec"<<endl;


and here is the result

# 0
thread 0
sleep 5sec
//the loop never goes to 2nd iteration

Thanks for help.

9th September 2008, 22:18
You are creating the thread on the stack inside the loop, so the object (and the thread behind it) gets killed before it has a chance to do anything. And you might be experiencing a crash if you never reach the second iteration of the loop.

9th September 2008, 22:43
You are right, I now use the signal/slot and QList to hold the trashthread, and each time I can release a small amount of trashthread (the real program takes large memory) each time when some trashthread finished. Thanks.