我们是否需要在收到来自 cond 变量的信号后解锁互斥锁?
Do we need to unlocking a mutex after recived a signal from cond variable?
我用 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
returns 互斥锁被锁定时,您可以安全地检查受其保护的共享状态:
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 语言制作了一个用于教育目的的应用程序,其中包含互斥锁和条件变量。
此处为简短示例:
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
returns 互斥锁被锁定时,您可以安全地检查受其保护的共享状态:
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()
orpthread_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
更改。一旦它改变并且您完成访问受互斥体保护的共享状态,必须解锁互斥体。