Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to release memory of Qthread object?

Tags:

c++

qt

qthread

I have done something like this:

//in the mainwindow's constructor
QThread *thr = new QThread;
soundWorker * work = new soundWorker;
connect(this,SIGNAL(playsound()),work,SLOT(process()));
work->moveToThread(thr);
thr->start();

Shall I delete thr and work at the deconstructor of mainwindow?

like image 505
Nyaruko Avatar asked Nov 03 '14 12:11

Nyaruko


2 Answers

You can use the default Qt way of managing memory by assigning a parent to the QThread, i.e. do this:

QThread *thr = new QThread(this);//the mainwindow's is now the thread parent

In Qt, parents are responsible for managing the memory of their children. Thus, the QThread will be automatically deleted when needed.

Then, for your soundWorker, you have a few different solutions. If its lifetime is the same as your mainwindow, as you hint when you ask if you should delete it in the destructor of the mainwindow, you could simply make it a non-pointer member, and its storage duration would then become automatically handled.

The parent thing is specific to Qt though. In general, when you deal with memory yourself, you should resort to wrappers (such as smart pointers) that enables RAII.

Further reading: Qt Trees and ownership model

like image 73
JBL Avatar answered Sep 19 '22 06:09

JBL


You can use the QThread::finished() signal in order detect the moment you wish to release the QThread pointer. Same thing could be done with QObject pointers which were moved to the new thread.

Considering that the moment of closing the main window is the moment of closing the whole application and considering that you don't need to further do processing after the application was closed, you can pass the main window pointer as a parent to the QThread by either passing it to the constructor or using QObject::setParent.

Releasing the resources acquired inside the thread handled by QThread must be handled separately as you can't make the QThread object a parent of a resource managed by it - QThread lives in the thread where it was created and not in the thread it manages.

More details here.

like image 43
Iuliu Avatar answered Sep 19 '22 06:09

Iuliu