I'm writing MT program for Linux in C++ and I want to know how thread cancellation is performed.
As far as I understand when thread is cancelled cleanup functions are called inside thread's function and the thread's function is forced to exit. This mean two things:
Am I right and code below ill work just fine?
One more question in code below, when thread is cancelled somewhere in SECTION A, second_thread_cleanup_function() will be called first, right?
class SomeObject
{
public:
~SimpleObject (void); // <- free dynamically allocated memory
void finalize (void);
// ...
}
void first_thread_cleanup_function (void* argument)
{
SomeObject* object (argument);
object->finalize ();
}
void second_thread_cleanup_function (void* argument)
{
// ... do something ...
}
void* thread_function (viod* argument)
{
SomeObject object;
pthread_cleanup_push (first_thread_cleanup_function, &object);
// ... some code ...
pthread_cleanup_push (second_thread_cleanup_function, NULL);
// ... SECTION A ...
pthread_cleanup_pop (0);
// .. some code ...
pthread_cleanup_pop (1);
}
With any modern linux distribution using NPTL (which in practice means any running a 2.6 kernel), NPTL will call destructors and unwind the stack with a pseudo-exception.
In fact NPTL insists on it, by implementing what it calls forced stack unwinding. You can catch the pseudo-exception with catch(...), but if you do so you must subsequently rethrow it or the whole process will be terminated.
Chris
Destructors will only be called assuming you free allocated objects in the cleanup methods. Otherwise, no.
And yes, you have the order of cleanup calls in section A correct.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With