I have a hierarchy of classes :
struct A
and struct B
, which is stored in an instance of A.
I run a method of A, which run a method of B, which downloads something asynchronously with connect signal of downloading to slot of B.
After that I don't use the A and B instances. They are saved in a vector.
What I need is to get information from object B about finishing of downloading (slot from B runs method A to notify it and save its data to A). After notification, the instance of B isn't needed anymore (it stores a lot of data, so I need to clear it). But no other threads know when should be done!
The thread, which calls slot B can't clear B object, because of the dangers of delete this
. Even if that thread sets some mutex (which can be placed in A), and another thread, which is waiting for all time to that mutex, will delete it - it is also dangerous, because the thread of the slot can be still running.
So, how can I safely delete the B instance, within slot of B notification?
I tried to create code example here (B - downloader, A - Storage):
struct Storage
{
Downloader *d; // createrd in ctor
Data data; // only value, not pointer (for some reasons).
//The same in 'Downloader'
int downloadedFiles; // 0 by ctor
void run() // think, main()
{
d->download(); // there is an array in my program.
//Here is one Downloader*, because it is example
}
void finishedDownload()
{
++downloadedFiles;
data = a->data;
// delete d; // wish, it would be done like that :(
// But the thread will be back to a->download()
}
}
struct Downloader
{
Data data;
Internet internet;
Storage *parent;
void download()
{
internet.set('http://someurl.dat');
connect( &internet, SIGNAL(downloaded()), this, SLOT(downloaded()) );
internet.download(&data); // async
}
public slots :
void downloaded()
{
parent->finishedDownload();
// And there is the finish of the thread, which was created by SIGNAL of Interget,
//but I need to delete 'Data data' from this struct.. How?
}
};