Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Multithreading pthread_cond_timedwait超时后,线程是否拥有互斥锁?_Multithreading_Pthreads_Posix_Condition Variable - Fatal编程技术网

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

Multithreading pthread_cond_timedwait超时后,线程是否拥有互斥锁?,multithreading,pthreads,posix,condition-variable,Multithreading,Pthreads,Posix,Condition Variable,线程调用pthread\u cond\u timedwait,并返回ETIMEDOUT,线程是否拥有互斥锁 我最初认为不会,但似乎我们必须调用pthread\u mutex\u unlock,即使在pthread\u cond\u timedwait返回ETIMEDOUT之后 报告说: 成功返回后,互斥锁应已被锁定,且应归调用线程所有 因此,在不成功返回(返回值!=0)时,我认为互斥锁是不被拥有的 但是,如果在ETIMEDOUT之后不调用pthread\u mutex\u unlock,则互斥锁

线程调用
pthread\u cond\u timedwait
,并返回
ETIMEDOUT
,线程是否拥有互斥锁

我最初认为不会,但似乎我们必须调用
pthread\u mutex\u unlock
,即使在
pthread\u cond\u timedwait
返回
ETIMEDOUT
之后

报告说:

成功返回后,互斥锁应已被锁定,且应归调用线程所有

因此,在不成功返回(返回值!=0)时,我认为互斥锁是不被拥有的

但是,如果在
ETIMEDOUT
之后不调用
pthread\u mutex\u unlock
,则互斥锁似乎处于中断状态(即我无法让另一个线程获取它,它只是暂停)

文档中也暗示了这一点,因为无论返回值为
pthread\u cond\u 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\u cond\u timedwait
之后获取互斥锁吗?这真的没有意义,因为调用必须阻塞超过指定的时间才能再次获取互斥锁。

您看到的是POSIX的旧版本。这是否澄清了案文:

发生此类超时时,
pthread_cond_timedwait()
仍应释放并重新获取互斥体引用的互斥体,并可能同时使用指向条件变量的条件信号

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

超时并不是防止互斥锁被保持太长时间,而是防止条件信号不能及时到达(通常,互斥锁只能保持较短的、相对确定的时间,而等待的条件可能会受到外部输入的影响)