mercredi 28 janvier 2015

c++ std::thread on stack

I have an object with a normal constructor. This may be bad practice--don't berate me--but the constructor has a lot of initialization to do. Much of this initialization can be performed asyncronously, so I am calling a new thread from within the constructor.


When the thread in initialized on the stack, it appears that the thread is destroyed when the constructor exits which causes a crash. This would look like so:



class MyObject
{
MyObject()
{
// Typical initialization
// ...

// Time consuming initialization
std::thread(&MyObject::Init; this); // Create new thread to call Init();

// Crash when exit MyObject() here
}

void Init()
{
// Time consuming operations
}
};


The alternative (which works) is to create the thread on the heap as such.



class MyObject
{
std::thread* StartupThread;

MyObject()
{
// Typical initialization
// ...

// Time consuming initialization
StartupThread = new std::thread(&MyObject::Init; this); // Create new thread to call Init();

// Crash when exit MyObject() here
}
~MyObject()
{
StartupThread->join();
delete StartupThread;
}

void Init()
{
// Time consuming operations
}

};




My Question


Is there any harm is leaving the unjoined & undisposed thread object alive for the lifetime of the object or should I try to clean it up as soon as Init() finishes?


Is there a way to "automatically" dispose the thread when it finishes so it isn't left hanging around?


Aucun commentaire:

Enregistrer un commentaire