当前位置: 技术问答>linux和unix
多线程下的同步函数调用方式
来源: 互联网 发布时间:2017-05-24
本文导语: 最近在看一个线程池的实现,看到线程同步部分,对于等待和通知的方式不是很理解,源代码如下: void Event::wait() { while(m_nCount 0) { pthread_cond_wait(&m_notify, &m_mutex); } m_nCoun...
最近在看一个线程池的实现,看到线程同步部分,对于等待和通知的方式不是很理解,源代码如下:
m_nCount 的初始值为 0.
为什么在调用 pthread_cond_wait 和 pthread_cond_signal 之前都对 m_nCount 做判断呢?
下面的方式又有什么问题呢:
void Event::wait()
{
while(m_nCount 0)
{
pthread_cond_wait(&m_notify, &m_mutex);
}
m_nCount++;
pthread_cond_signal(&m_wait);
}
m_nCount 的初始值为 0.
为什么在调用 pthread_cond_wait 和 pthread_cond_signal 之前都对 m_nCount 做判断呢?
下面的方式又有什么问题呢:
void Event::wait()
{
pthread_cond_wait(&m_wait, &m_mutex);
}
void Event::notify()
{
pthread_cond_signal(&m_wait);
}
|
m_nCount 确保他两不能同时运行,确保一个在发的时候一个肯定在等收,确保信号一定收到~~
后面那两种方式,如果调了两次发送,但接受只接受了一次,后面那个信号就漏了
后面那两种方式,如果调了两次发送,但接受只接受了一次,后面那个信号就漏了
|
上面的代码wait()和notify()都会根据m_nCount的值堵塞,m_nCount的判断就是来做这个阻塞条件的 下面那个代码只是单纯的条件变量,可以理解为互斥锁,只要调用wait就阻塞
|
are you sure there is no pthread_mutex_lock and pthread_mutex_unlock calls in functions wait() and notify()? Maybe there are two other member functions that handle lock/unlock? Otherwise, the codes will be weird...
m_nCount can be considered as a shared resource. notify() and wait() are meant to be executed in different threads. Since they both need to know the status of m_nCount, a conditional variable is introduced here to synchronize on the value of m_nCount.
The codes you proposed miss the point of using conditional wait. a pthread_mutex_lock is sufficient, isn't it?
Why we need conditional wait? You don't want to waste cup cycle to keep checking the status of a value. If Pthreads didn't offer condition variables, but only provided mutexes, threads would need to poll the variable to determine when it reached a certain state.
m_nCount can be considered as a shared resource. notify() and wait() are meant to be executed in different threads. Since they both need to know the status of m_nCount, a conditional variable is introduced here to synchronize on the value of m_nCount.
The codes you proposed miss the point of using conditional wait. a pthread_mutex_lock is sufficient, isn't it?
Why we need conditional wait? You don't want to waste cup cycle to keep checking the status of a value. If Pthreads didn't offer condition variables, but only provided mutexes, threads would need to poll the variable to determine when it reached a certain state.