PDA

View Full Version : Threads problem



boss_bhat
26th July 2006, 11:11
Hi all,
I am new to Threads!! I have a class derived from QWidget and it runs a thread
which prints out messages. I use start, sleep, resume and terminate button to
controle the thread. I dont know how to controle `sleep and resume` of thread.
Here is the piece of code I have written,

ThreadWidget::ThreadWidget(QWidget *parent )
:QWidget(parent)
{

thinThread = new ThinThread();

QPushButton *startButton= new QPushButton("start",this);
QPushButton *sleepButton= new QPushButton("sleep",this);
QPushButton *resumeButton= new QPushButton("resume",this);
QPushButton *terminateButton = new QPushButton("terminate",this);

connect (startButton,SIGNAL (clicked()), thinThread, SLOT(start()));
connect (terminateButton,SIGNAL (clicked()), thinThread, SLOT(terminate()));
//connect (resumeButton,SIGNAL (clicked()), ??;
//connect (sleepButton,SIGNAL (clicked()), ??;

QHBoxLayout *mainLayout = new QHBoxLayout(this);

mainLayout->addWidget(startButton);
mainLayout->addWidget(sleepButton);
mainLayout->addWidget(resumeButton);
mainLayout->addWidget(terminateButton);

setLayout(mainLayout);

}

//ThinThread is derived from QThread!!

void ThinThread ::run ()
{
while(1)
{
sleep(1);
cout <<" in the thread\n";
}

}

Can some body explain how to do it?

Thanks in advance,
Boss

jpn
26th July 2006, 11:42
Can some body explain how to do it?
Start of by reading Thread Support in Qt (http://doc.trolltech.com/4.1/threads.html). Then, see Qt's threading examples at /examples/threads.

A few hints:

if you really want it to enter to an infinite loop inside run(), you'll need wait conditions
another (and maybe easier) option would be to enter to an event loop instead

boss_bhat
2nd August 2006, 14:07
I did something like this, it works fine but is this the right way of doing ??


void ThinThread ::run ()
{

label:

while(suspFlag)
{
sleep(1);
cout <<" in the thread "<< endl;
}
if (!suspFlag)
{
while (!suspFlag)
{
sleep(1);
}
}

goto label;

cout <<"done with the thread\n";
}

void ThinThread::suspend()
{
suspFlag=false;
}
void ThinThread::resume()
{
suspFlag=true;

}

please suggest me on this :)
Thanks in advance,
Boss

jacek
2nd August 2006, 15:41
I did something like this, it works fine but is this the right way of doing ??
Better use QWaitCondition.

And please use the [ code ] tags.