我想在完成进程去初始化之前取消一个线程,如下所示。
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
}
问题是,虽然在这里设置了PTHREAD_CANCEL_ASYNCHRONOUS,但真正的线程取消总是在authSessionListDeInit()之后发生,除非我在其间强制使用usleep()。
我的理解是取消应该在通过pthread_cancel()发送取消请求后立即发生,不应该吗?
如果我的理解不正确,如何在调用authSessionListDeInit()之前确保线程被取消?