The following code is my writing method:
Static bool alive = true;
Static int count = 0;
Pthread_mutex_t mutex;
Pthread_cond_t cond;
Void producer ()
{
Pthread_mutex_lock (& mutex); // Add a mutex lock
//... Do something here, queue. insert ()... or create something...
Count ++;
// If the write is as follows, consumer blocks to pthread_mutex_lock (& mutex)
// Obtain control of the mutex lock before pthread_cond_wait (& cond, & mutex.
Pthread_mutex_unlock (& mutex); // unmutex lock
Pthread_cond_signal (& cond); // wake up wait (). If there is no wait, do nothing.
// If the write is as follows, consumer blocks to pthread_mutex_lock (& mutex)
// Obtain the control of the mutex lock when pthread_cond_wait (& cond, & mutex) is possible.
Pthread_cond_signal (& cond); // wake up wait (). If there is no wait, do nothing.
Pthread_mutex_unlock (& mutex); // unmutex lock
}
Void consumer ()
{
Pthread_mutex_lock (& mutex); // Add a mutex lock
While (alive & 0 = count) {// wait only when count = 0, while () is not if (). It must be while after testing, why?
// Because pthread_cond_wait (& cond, & mutex) is divided into unlock-> wait-> lock. When a producer is like the first writing order, even if signal is obtained,
// If you cannot obtain the control of the mutex lock, the lock will be blocked, which is equivalent to rolling back two rows to pthread_mutex_lock (& mutex );
Pthread_cond_wait (& cond, & mutex); // unlock the mutex lock to sleep. After waking up, the mutex lock is automatically applied back.
}
//... Do something here, queue. get ()... or use & delete something
Count --;
Pthread_mutex_lock (& mutex); // unmutex lock
} Reprinted please indicate the source, thank you: http://blog.csdn.net/sprintfwater/article/details/21190859