gpt4 book ai didi

c - 我们是否需要在收到来自 cond 变量的信号后解锁互斥锁?

转载 作者:太空宇宙 更新时间:2023-11-04 12:05:19 25 4
gpt4 key购买 nike

我用 C 语言制作了一个应用程序,用于教育目的,使用互斥锁和条件变量。

这里是一个简短的例子:

while (!(is_done == 0))         
pthread_cond_wait(&cond, &mutex);

pthread_mutex_unlock(&mutex);

你能解释一下吗,为什么在“while”语句(并从第二个线程接收到信号)之后我们需要解锁互斥锁,当信号使互斥锁被锁定时?

我从网上的很多例子中得到它,但是当我想在收到信号后使用互斥量时,我需要解锁互斥量吗? Ofc 我想在收到信号后处理这个线程

最佳答案

Can you explain me, why after "while" statment (and recived signal from second thread) we need to unlock the mutex, when signal makes that mutex is locked?

pthread_cond_wait返回互斥量被锁定,以便您可以安全地检查受其保护的共享状态:

These functions atomically release mutex and cause the calling thread to block on the condition variable cond; atomically here means "atomically with respect to access by another thread to the mutex and then the condition variable". That is, if another thread is able to acquire the mutex after the about-to-block thread has released it, then a subsequent call to pthread_cond_broadcast() or pthread_cond_signal() in that thread shall behave as if it were issued after the about-to-block thread has blocked.

Upon successful return, the mutex shall have been locked and shall be owned by the calling thread. If mutex is a robust mutex where an owner terminated while holding the lock and the state is recoverable, the mutex shall be acquired even though the function returns an error code.

通常,应尽快解锁互斥量以减少争用。

在您的情况下,您等待共享状态 is_done 更改。一旦它发生变化并且您已完成访问受互斥量保护的共享状态,则必须解锁互斥量。

关于c - 我们是否需要在收到来自 cond 变量的信号后解锁互斥锁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50945546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com