Multithreading revisited
-
I started a post here "here":http://developer.qt.nokia.com/forums/viewthread/4609/ but after digging and analysing a bit more it seems that there is no solution ... at least that i don't know ... in wich the threads have some memory leak stuff thingy.
"This is the link to my packed project ":http://www.mediafire.com/file/os5hkg71r33nqzm/Threadz.rar
Does anyone have a clear example of a program that makes and stops thousands of threads over time(threads that have a timer, a socket or anything else in them) and don't eat up RAM?
Please post just one working example or slightly modify the files i provided.
My compiled example reaches ~9Mb in about 20 minutes of continuous work -
Hi SineaNT,
if this is realated to the othe rtopic, please use the same thread.
If you want to stop threads and don't want to have memory leaks, it's a trivial thing. Implement it.@
MyThread::run
{
while(!m_bStopThread)
{
// do stuff
// do the wait in wait conditions
}
// do cleanup
}MyThread::fooToStop()
{
m_bStopThread = true;
// trigger the wait in wait condition
}
@ -
Well ... now the run method looks like
@void Thread::run()
{
QTimer t;connect(&t, SIGNAL(timeout()), this, SLOT(onTimer())); t.setInterval(1000); t.start(); while(isRuning) { QCoreApplication::processEvents(); this->msleep(1); } disconnect(&t, SIGNAL(timeout()), this, SLOT(onTimer())); t.stop();
}
@and still leaks :|
-
There are some bugs in this code:
connect an object from inside the thread to a slot of the thread object: The slot is run in the main event loop, not inside the thread!
inside a thread, never call QCoreApplication::processEvents();! This is the main event loop, not a thread event loop.
who sets isRunning to false?
QCoreApplication::processEvents() will not return untile you quit the event loop
Please read a bit more about threadding in Qt and event loops. The article in the "wiki":http://developer.qt.nokia.com/wiki/Threads_Events_QObjects of pepe is a good entry point.
-
Indeed. SineaNT: You Are Doing It Wrong (TM). Google for that phrase in combination with "qt" "and thread" and you'll know what I mean, and what problem the wiki entry Gerolf refered you to discusses.
Note that if you talk about creating and destroying thousands of threads, you're doing more wrong than just how you use those threads. You have a major design problem. Look into the concept of thread pools. It is not like threads come for free. They cost resources to create and maintain.
-
-
Anyone using multi threading is in a for a load of problems if you're not really, really careful and know what you are doing. I know I was when I first started with it! Anyway, that's how you learn, I guess. So be prepared you'll get more problems related to threading than you can possibly anticipate now.