16.5 Bounded Buffer Implementation Using Condition Variables

Team-FLY

16.5 Bounded Buffer Implementation Using Condition Variables

Program 16.10 gives a condition variable implementation of a bounded buffer that is similar to the semaphore implementation of Program 16.6.

Program 16.10 buffercond.c

Condition variable implementation of a bounded buffer .

 #include <pthread.h> #include "buffer.h" static buffer_t buffer[BUFSIZE]; static pthread_mutex_t bufferlock = PTHREAD_MUTEX_INITIALIZER; static int bufin = 0; static int bufout = 0; static pthread_cond_t items = PTHREAD_COND_INITIALIZER; static pthread_cond_t slots = PTHREAD_COND_INITIALIZER; static int totalitems = 0; int getitem(buffer_t *itemp) { /* remove an item from buffer and put in itemp */    int error;    if (error = pthread_mutex_lock(&bufferlock))       return error;    while ((totalitems <= 0) && !error)       error = pthread_cond_wait (&items, &bufferlock);    if (error) {       pthread_mutex_unlock(&bufferlock);       return error;    }    *itemp = buffer[bufout];    bufout = (bufout + 1) % BUFSIZE;    totalitems--;    if (error = pthread_cond_signal(&slots)) {       pthread_mutex_unlock(&bufferlock);       return error;    }    return pthread_mutex_unlock(&bufferlock); } int putitem(buffer_t item) {                  /* insert an item in the buffer */    int error;    if (error = pthread_mutex_lock(&bufferlock))       return error;    while ((totalitems >= BUFSIZE) && !error)       error = pthread_cond_wait (&slots, &bufferlock);    if (error) {       pthread_mutex_unlock(&bufferlock);       return error;    }    buffer[bufin] = item;    bufin = (bufin + 1) % BUFSIZE;    totalitems++;    if (error = pthread_cond_signal(&items)) {       pthread_mutex_unlock(&bufferlock);       return error;    }    return pthread_mutex_unlock(&bufferlock); } 

Program 16.10 is simpler than the semaphore implementation because condition variables have static initializers. Test Program 16.10 on a producer-consumer problem by linking it with Programs 16.7, 16.8 and 16.9. It also needs Program 13.4 ( globalerror ), Program 13.2 ( randsafe ) and Program 13.5 ( sharedsum ).

Team-FLY


Unix Systems Programming
UNIX Systems Programming: Communication, Concurrency and Threads
ISBN: 0130424110
EAN: 2147483647
Year: 2003
Pages: 274

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net