Reputation: 1238
I have a main thread that I create some self-contained class instances in.
The instances themselves contain a lot of data, and need to be deleted and recreated often. The actual deletion of them takes a while (100k instances containing a lot of data == long deletion time), so I had the idea of just offloading the deletion of them to a separate thread and therefore allowing the UI to stay responsive while they are being deleted and memory is cleaned up.
Here's some pseudocode showing the class I want to delete:
class myObj
{
std::vector<int> bigData; //eventually filled with lots of data
};
Here's some pseudocode to show how the default blocking deletion method works:
void deleteStuff (std::vector<myObj*> *objects) //this works fine
{
for (auto obj : *objects)
{
delete obj;
}
objects->clear();
}
But when I delete things this way, my program crashes. Why?
void deleteStuffThreaded(std::vector<myObj*> *objects)
{
for (auto obj : *objects)
{
delete obj;
}
objects->clear();
}
void deleteStuff(std::vector<myObj*> *objects) //this crashes
{
std::thread deleteThread(&deleteStuffThreaded, objects);
}
It's worth noting that the "objects" vector is never touched again once deleteStuff returns, so it's not a race condition happening elsewhere in the code between "objects" being cleared in the thread and it being accessed elsewhere. Also sometimes the "deleteStuffThreaded" function crashes before getting to the "clear" line when I step through the code.
Google tells me it's theoretically possible to delete objects in different threads than the one they were created in, and I know the crash isn't caused by trying to access properties of one of the deleted objects after "deleteStuff" returns, because the single-threaded version works fine (and I've checked my code and those instances are never touched again).
Upvotes: 0
Views: 493
Reputation: 229108
The std::thread
destructor docs say:
~thread(); (since C++11)
Destroys the thread object.
If *this has an associated thread (joinable() == true), std::terminate() is called.
So since you have not joined or detached the thread, the program will terminate when your deleteStuff
function ends and the destructor of the thread object is called
Since you likely want to fire and forget about your thread, do:
std::thread deleteThread(&deleteStuffThreaded, objects);
deleteThread.detach();
Upvotes: 2