0

I have a class that is inherited from QThread (lets called it ClassA) that is running in a for loop like following:

for(int i=0;i<somenumber;i++)
{
    ClassA* classa = new ClassA();

    classa->execute(); // just a normal direct function call

    classa->exit();
    classa->deleteLater();
}

The problem is that the classa contains a lot of memory, and it does not seem being destroyed while the loop is still running. So the program will crash soon after the memory has built up (like memory leak). I tried to use "delete classa" as well which of course will crash the program.

Anybody know how to properly run and delete such class in a loop so it won't be occupying memory constantly.

The for loop also sits in another thread. So there is a thread hierarchy where event loop might be key in calling deleteLater()? The code is a bit too complex to write up, but the quickest answer I want might be how to delete the Qthread object properly in a threading environment (i.e. using eventloop properly) so there is no memory leak (or more like memory building up as the Qthread object is not deleted)

John Yang
  • 547
  • 1
  • 8
  • 21
  • [Post a Minimal, Complete, Valid Example](http://stackoverflow.com/help/mcve). – Rakib Jun 11 '14 at 05:37
  • The code is a bit too complex to write up, but the quickest answer I want might be how to delete the Qthread object properly in a threading environment (i.e. using eventloop properly) so there is no memory leak (or more like memory building up as the Qthread object is not deleted) – John Yang Jun 11 '14 at 08:14

1 Answers1

0

In the case that you reimplemented run(), you can always wait() for the thread to finish. I'm assuming that your method execute() calls start(). Then you can savely delete it directly (using your example code):

for(int i=0;i<somenumber;i++)
{
    ClassA* classa = new ClassA();

    classa->execute(); // just a normal direct function call

    classa->exit();
    classa->wait(); // wait till the QThread is finished
    delete classa; // immediately free resources
}
Martin Hennings
  • 16,418
  • 9
  • 48
  • 68