Multithreaded server
-
Hello
I'm building(or at least trying) a server side app with Qt and i'm a bit stuck with the threads. I have the folowing classes:
@#ifndef CLUSTER_H
#define CLUSTER_H#include <QObject>
#include <QMutex>
#include "thread.h"class Cluster : public QObject
{
Q_OBJECT
public:
Cluster(QObject parent = 0);
QList<Thread> threads;
signals:public slots:
void onTimer();
void garbageCollect();};
#endif // CLUSTER_H
@@#include "cluster.h"
#include "thread.h"
#include <QTimer>
#include "qdebug.h"Cluster::Cluster(QObject *parent) : QObject(parent)
{QTimer * timer = new QTimer(); timer->setInterval(1); connect(timer, SIGNAL(timeout()), this, SLOT(onTimer())); timer->start(); QTimer * gc = new QTimer(); gc->setInterval(10); connect(gc, SIGNAL(timeout()), this, SLOT(garbageCollect())); gc->start();
}
void Cluster::onTimer()
{
threads.append( new Thread() );
threads[threads.count()-1]->start();
qDebug() << "Cluster has " << threads.count();
}void Cluster::garbageCollect()
{
for(int i = 0; i < threads.count(); i++)
{
if(threads[i]->isFinished())
{
delete threads.takeAt(i);
garbageCollect();
break;
}
}
}
@@#ifndef THREAD_H
#define THREAD_H#include <QObject>
#include <QThread>
#include <QTimer>class Thread : public QThread
{
Q_OBJECT
public:
Thread(QObject *parent = 0);
~Thread();
void run();
QTimer * timer;signals:
public slots:
void onTimer();
void init();};
#endif // THREAD_H
@@#include "thread.h"
#include "QTimer"
#include "qdebug.h"Thread::Thread(QObject *parent)
{
}Thread::~Thread()
{
timer->stop();
disconnect(timer, SIGNAL(timeout()), this, SLOT(onTimer()));
delete timer;
}void Thread::run()
{
QTimer::singleShot(10, this, SLOT(init()));
exec();
}void Thread::init()
{
timer = new QTimer(this);
timer->setInterval(1);
connect(timer, SIGNAL(timeout()), this, SLOT(onTimer()));
timer->start();
}void Thread::onTimer()
{
this->quit();
}
@The above code is just a simplified version.
My problem is that although i delete the threads, and in the Thread destructor i stop, disconect and delete the timer it still builds up memory, if i don't use the timer it stays at the same memory usage.
Any ideas of how i should corectly delete the per thread timer ? Or any other objects used by each thread(i will have QSslSockets and others)
-
Don't add slots to QThread subclasses.
-
Thanks mate, worked like a charm.
For anyone having the same problem in the future, this is how i solved the problem:
I made a class that made all the work(wich "lives" in the thread) and then run method of the class looks like
@void Thread::run()
{
client = new Wrapped();
while(client->isAlive)
{
sleep(1000); // depending on OS
}
}@