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

时间:2016-10-20 12:06:37

标签: multithreading pthreads posix condition-variable

线程调用pthread_cond_timedwait后返回ETIMEDOUT,线程是否拥有互斥锁?

我最初会认为不是,但即使在pthread_mutex_unlock返回pthread_cond_timedwait之后,我们仍然必须致电ETIMEDOUT

documentation说:

  

成功返回后,互斥锁应被锁定,并由调用线程拥有。

因此,在非成功返回(返回值!= 0)时,我认为互斥锁不属于。

但是,如果我们在pthread_mutex_unlock之后没有调用ETIMEDOUT,则互斥锁似乎处于断开状态(即我无法获得另一个线程来获取它,它只是停止)。

文档也提示这一点,因为无论pthread_cond_timedwait的返回值是什么,总是解锁互斥锁:

(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之后获取互斥锁?它没有多大意义,因为为了再次获取互斥锁,调用必须阻止超过指定的时间。

1 个答案:

答案 0 :(得分:5)

You are looking at an older issue of POSIX. Issue 7 has this clarified text:

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.

If it didn't reacquire the mutex in this case you'd have to re-acquire it in the calling code anyway so you could re-test the condition after a timeout, because you might have consumed a condition signal. It's only if the condition you're waiting for hasn't occurred and a timeout occurred that you should treat it as the timeout case.

The timeout isn't guarding against the mutex being held for overly long, it's guarding against a condition signal not arriving in a timely manner (generally, the mutex should only be held for short, relatively deterministic periods whereas the condition being waited for might be influenced by external inputs).