Synchronization Using Mutexes and Condition Variables

 [Previous Chapter]  [Previous Page]  [Contents]  [Next Page]  [Next Chapter]

template<class Token>
void RingBuffer<Token>::add(Token& token) {
   if (filled == buffer.size()) {
      pthread_cond_wait(&nonFull, &mutex);
   assert(filled < buffer.size());
   buffer[in] = token;
   in = (in + 1) % buffer.size();
} // add

*All methods of a concurrently used class must protect accesses on their data members with a mutex variable.
*pthread_mutex_lock blocks the calling thread until the given mutex becomes available and locks it.
*pthread_mutex_unlock unlocks it and allows one of the other threads to proceed that waited for this mutex to become available, if any.
*This is not sufficient for add, however, as we cannot proceed if the buffer is full. In this case, we want to wait until the buffer is emptied by one of the consumers.

 [Previous Chapter]  [Previous Page]  [Contents]  [Next Page]  [Next Chapter]
Copyright © 2001, 2002 Andreas Borchert, converted to HTML on February 21, 2002