-
Notifications
You must be signed in to change notification settings - Fork 3.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
条件变量中对wait代码的一个疑问 #249
Comments
这一块我也认为有问题,按道理来说调用phtread_cond_wait之前是需要调用pthread_mutex_lock来进行加锁的,而pthread_cond_wait调用在等待条件发生期间会阻塞线程并对mutex进行解锁操作,以避免忙等待问题;而作者最开始很明显也是加了锁的,后面不知道为什么给pthread_cond_wait的锁注释掉了,这不会导致线程安全问题和竞态条件吗? |
我也有同样的疑问,而且作者在庖丁解牛1中也说了要先加锁,实际代码确注释掉了,同学现在解决了这个问题嘛? |
嗯,我记得之前看到哪块代码调用了wait,并且那块逻辑需要加锁,为了避免在调用wait前加一次锁进入wait又加一次锁的双重锁死锁问题,所以作者把里面的锁给注释了。主要是这个普通的mutex不支持重复加锁,这一块的逻辑不是很严谨,但是应该作者为了代码易懂,所以没用高级锁 |
我也看到了,是这样的,多谢同学 |
bool wait(pthread_mutex_t *m_mutex)
{
int ret = 0;
//pthread_mutex_lock(&m_mutex);
ret = pthread_cond_wait(&m_cond, m_mutex);
//pthread_mutex_unlock(&m_mutex);
return ret == 0;
}
请问这边为什么不直接 return pthread_cond_wait(&m_cond, m_mutex) == 0;
The text was updated successfully, but these errors were encountered: