test-buffer.h

A simple Monitor class using posix threads. The following defines a Buffer monitor with protected get() and put() access.

See also:
Dv::Thread::Thread
// $Id: test-buffer.h,v 1.3 2008/12/21 09:40:47 dvermeir Exp $
#ifndef DV_THREAD_BUFFER_H
#define DV_THREAD_BUFFER_H
// $Id: test-buffer.h,v 1.3 2008/12/21 09:40:47 dvermeir Exp $
#include <dvthread/lock.h>

// This class represents a buffer with synchronized access.
class Buffer: public Dv::Thread::Monitor {
  public:       
    static const std::string GET; // ("get");
    Buffer(): Dv::Thread::Monitor("buffer",2), // &std::cerr),
      n_items_(0) {}
    // Add an item to a buffer.
    void put(int i) {
      Dv::Thread::Lock lock(*this, "put"); // Get exclusive access to *this.
      while (n_items_==MAX)
        if (!wait(OK_TO_PUT,2000)) // Wait at most 2 secs.
          throw std::runtime_error("Buffer::put() timed out");
      std::cerr << "put " << i << " ";
      data_[n_items_++] = i; // Actually put the item.
      signal(OK_TO_GET);
    }
  
     // Obtain and remove the last item in the buffer.
    int get() {
      Dv::Thread::Lock lock(*this); // , &std::cerr); // Get exclusive access to *this.
      while (n_items_ == 0) {
        if (!wait(OK_TO_GET, 2000)) 
          throw std::runtime_error("Buffer::get() timed out");
      }
      int tmp = data_[--n_items_];
      std::cerr << GET  << tmp << " ";
      signal(OK_TO_PUT);
      return tmp;
    }

  private:
    // Buffer capacity.
    enum { MAX = 3 };
    // Names for conditions.
    enum { OK_TO_GET = 0, OK_TO_PUT = 1 }; /// conditions 
    // Number of items in the buffer.
    int n_items_;
    // Actual store for items.
    int data_[MAX];
};
#endif

dvthread-0.13.4 [11 December, 2009]