first of all "proper" because I presume people will tell me that it is a bad practice to launch thread from a class. :) So I'm wondering what is the best way of stopping a infinite thread in a destructor. Wrapping function that thread calls in try and throwing exception when flag shutdown is set? Just good old int/enum? Good new std::atomic int? Something else? Now I use:
//in destructor I call terminate member func
void terminate()
{
currentStatus=terminating;
std::cout<<"trying to kill"<<std::endl;
while (currentStatus!=terminated)
std::this_thread::yield();
std::cout<<"MISSION ACOMPLISHED"<<std::endl;
}
And the function that thread runs is:
while (currentStatus==active)
{
//...
}
currentStatus=terminated;
currentStatus is an enum:
enum status{
active,
terminating,
terminated
};
'I presume people will tell me that it is a bad practice to launch thread from a class' - not me, anyway. If you have OO language, where else would you start it from :)
There is an issue with a yield() loop. If the thread calling the destructor has a higher priority than the thread being terminated, your design could livelock forever on a single-processor system. Even on a multi core system, there could be a longish delay. Better to wait on the thread handle or some event that the terminating thread sets as its last action before exit. Not only does that remove the avoidable CPU-looping, it also dodges any cacheing issues with the 'status' emum that might require explicit barriers.
Rgds, Martin