pthread_cond_timedwait 超时后线程是否拥有互斥量?

Does a thread own a mutex after pthread_cond_timedwait times out?

在线程调用 pthread_cond_timedwait 后,它 returns ETIMEDOUT,线程是否拥有互斥体?

我最初认为不,但看起来我们 必须 调用 pthread_mutex_unlock 即使在 pthread_cond_timedwait returns ETIMEDOUT.

documentation 说:

Upon successful return, the mutex shall have been locked and shall be owned by the calling thread.

因此,在不成功的情况下 return(return 值!= 0),我认为互斥体不属于自己。

但是,如果我们在 ETIMEDOUT 之后不调用 pthread_mutex_unlock,则互斥体似乎处于损坏状态(即我无法让另一个线程获取它,它只会停止)。

文档也暗示了这一点,因为它们 总是 解锁互斥量,而不管 pthread_cond_timedwait 的 return 值:

(void) pthread_mutex_lock(&t.mn);
                t.waiters++;
        clock_gettime(CLOCK_REALTIME, &ts);
        ts.tv_sec += 5;
        rc = 0;
        while (! mypredicate(&t) && rc == 0)
                rc = pthread_cond_timedwait(&t.cond, &t.mn, &ts);
        t.waiters--;
        if (rc == 0) setmystate(&t);
(void) pthread_mutex_unlock(&t.mn);

那么,线程是否总是在 pthread_cond_timedwait 之后获取互斥量?这实际上没有意义,因为调用必须阻塞超过指定时间才能再次获取互斥量。

您正在查看 POSIX 的较旧一期。 Issue 7 有此澄清文本:

When such timeouts occur, pthread_cond_timedwait() shall nonetheless release and re-acquire the mutex referenced by mutex, and may consume a condition signal directed concurrently at the condition variable.

如果在这种情况下它没有重新获取互斥锁,您无论如何都必须在调用代码中重新获取它,以便您可以在超时后重新测试条件,因为您可能已经消耗了条件信号.只有当您等待的条件没有发生并且发生超时时,您才应将其视为超时情况。

超时不是防止互斥量被保持过长,它是防止条件信号没有及时到达(通常,互斥量应该只保持较短的,相对确定的时间,而条件正在等待可能会受到外部输入的影响)。