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"
- {
- Q_OBJECT
- public:
- signals:
- public slots:
- void onTimer();
- void garbageCollect();
- };
- #endif // CLUSTER_H
- #include "cluster.h"
- #include "thread.h"
- #include <QTimer>
- #include "qdebug.h"
- {
- timer->setInterval(1);
- connect(timer, SIGNAL(timeout()), this, SLOT(onTimer()));
- timer->start();
- 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>
- {
- Q_OBJECT
- public:
- ~Thread();
- void run();
- signals:
- public slots:
- void onTimer();
- void init();
- };
- #endif // THREAD_H
- #include "thread.h"
- #include "QTimer"
- #include "qdebug.h"
- {
- }
- Thread::~Thread()
- {
- timer->stop();
- disconnect(timer, SIGNAL(timeout()), this, SLOT(onTimer()));
- delete timer;
- }
- void Thread::run()
- {
- exec();
- }
- void Thread::init()
- {
- 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)
2 replies
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
- }
- }
You must log in to post a reply. Not a member yet? Register here!


