pthread取消激活时间

时间:2012-03-17 23:05:54

标签: c pthreads

我想在完成进程去初始化之前取消一个线程,如下所示。

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()之前确保线程被取消?

2 个答案:

答案 0 :(得分:1)

来自docs

  

目标线程中的取消处理应该运行   与从中返回的调用线程异步   pthread_cancel可以()。

所以pthread_cancel可以在取消发生之前返回,这意味着你的假设是错误的。

您可以考虑使用取消标志和/或条件变量来表示函数实际结束时更流行且可以说更安全的方法(pthread_cancel失败的风险),而不是使用pthread_cancel。

答案 1 :(得分:0)

不,取消发生在cancellation points,例如。系统调用,libc调用 - 查看函数文档(例如accept()close()),或者查看here

相关问题