PDA

View Full Version : How can I implent an thread manager?



howie1013
18th June 2009, 11:04
I do something in MyThread, the main run() is infinite loop until stop() is called(canRun change to false)
ThreadManager is a class which manger threads. When sometime calls Delete(MyThread * thr), "thr" will be pushed in a queue, and the main run() of ThreadManager get a MyThread pointer from the queue and delete the thread.

I want to block the thread of ThreadManager until "thr" can be deleted, my problem is I don't know when "thr" is terminated.

This is my code here.
Thanks for any suggestions.


class MyThread : public QThread
{
public:
MyThread() { canRun = true; }

void run()
{
while(canRun)
{
msleep(50);
/* do something */
}
exec();
}
void stop() { canRun = false; }
private:
bool canRun;
};


class ThreadManager : public QThread
{
public:
void run()
{
MyThread * thr;
queue.clear();
while(true)
{
msleep(50);
while(!queue.isEmpty())
{
thr = queue.dequeue();
thr->stop();
/* I want to block this thread until
* "thr" terminated(can be deleted) */
delete thr;
}
}

}

MyThread * New() { return (new MyThread); }
void Delete(MyThread * thr) { queue.push_back(thr); }

private:
QQueue<MyThread*> queue;
};

shentian
18th June 2009, 12:29
The following line should do (using QThread::wait):


thr->wait();

shentian
18th June 2009, 12:48
You should maybe also have a look at the QThreadPool class and the Mandelbrot example that comes with Qt.