I wanted to cancel a thread right before the process de-initialization is done, like the following.
rc2 = pthread_attr_init(&attr);
ERR_IF( rc2 != 0 );
rc2 = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
ERR_IF( rc2 != 0 );
rc2 = pthread_create(&destroy_thread, &attr, destroy_expired_sessions, NULL);
ERR_IF( rc2 != 0 );
...
rc2 = pthread_cancel(destroy_thread);
ERR_IF( rc2 != 0 );
usleep(10); // without the sleep here, the real cancellation will be postponed.
rc2 = authSessionListDeInit();
ERR_IF( rc2 != 0 );
...
static void *destroy_expired_sessions(void *t)
{
int rc2 = 0;
(void)t;
pthread_cleanup_push(cleanup_handler, NULL);
rc2 = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
if (rc2 != 0)
AUTH_DEBUG5("pthread_setcancelstate(): rc2 == %d\n", rc2);
rc2 = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
if (rc2 != 0)
AUTH_DEBUG5("pthread_setcanceltype(): rc2 == %d\n", rc2);
... // real work of the thread is done here
}
The problem is, although PTHREAD_CANCEL_ASYNCHRONOUS is set here, the real thread cancellation always happens after authSessionListDeInit(), unless I force a usleep() in between.
My understanding is the cancellation should happen right after the cancel request is sent through pthread_cancel(), shouldn't it?
If my understanding is not correct, how to ensure the thread gets cancelled before authSessionListDeInit() is called?