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