Bounded Buffer with Condition Variables

Bounded Buffer with Condition Variables - Bounded Buffer...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
Bounded Buffer with Condition Variables #include <pthread.h> enum {MaxSize = 10}; class BoundedBuffer{ int _queue[MaxSize]; int _head; int _tail; int _n; mutex_t _mutex; cond_t _emptyCond; cond_t _fullCond; public: BoundedBuffer(); BoundedBuffer:: BoundedBuffer() { _head = 0; _tail = 0; _n = 0; pthtread_mutex_init(&_mutex, NULL, NULL); cond_init(&_emptyCond, USYNC_THREAD, NULL); cond_init(&_fullCond, USYNC_THREAD, NULL); }
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
with Condition Variables void BoundedBuffer:: enqueue(int val) { mutex_lock(_mutex); // Wait if queue is full while (_n == MaxSize) { // queue is full cond_wait(&_fullCond, &_mutex); } // There is space in queue _queue[_tail]=val; _tail = (_tail+1)%MaxSize; _n++; // Wake up a thread waiting in // dequeue if any cond_signal(_emptyCond); mutex_unlock(_mutex); } int * BoundedBuffer:: dequeue() { mutex_lock(_mutex); // Wait if queue is empty while (_n==0) { &_mutex); } // queue is not empty int val = _queue[_head]; _head = (_head+1)%MaxSize;
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 01/30/2012 for the course CS 354 taught by Professor Staff during the Fall '08 term at Purdue.

Page1 / 10

Bounded Buffer with Condition Variables - Bounded Buffer...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online