My preliminary exploration of thread condition Variables

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.