00001 // $Id: test-buffer.h,v 1.3 2008/12/21 09:40:47 dvermeir Exp $ 00002 #ifndef DV_THREAD_BUFFER_H 00003 #define DV_THREAD_BUFFER_H 00004 // $Id: test-buffer.h,v 1.3 2008/12/21 09:40:47 dvermeir Exp $ 00005 #include <dvthread/lock.h> 00006 00007 // This class represents a buffer with synchronized access. 00008 class Buffer: public Dv::Thread::Monitor { 00009 public: 00010 static const std::string GET; // ("get"); 00011 Buffer(): Dv::Thread::Monitor("buffer",2), // &std::cerr), 00012 n_items_(0) {} 00013 // Add an item to a buffer. 00014 void put(int i) { 00015 Dv::Thread::Lock lock(*this, "put"); // Get exclusive access to *this. 00016 while (n_items_==MAX) 00017 if (!wait(OK_TO_PUT,2000)) // Wait at most 2 secs. 00018 throw std::runtime_error("Buffer::put() timed out"); 00019 std::cerr << "put " << i << " "; 00020 data_[n_items_++] = i; // Actually put the item. 00021 signal(OK_TO_GET); 00022 } 00023 00024 // Obtain and remove the last item in the buffer. 00025 int get() { 00026 Dv::Thread::Lock lock(*this); // , &std::cerr); // Get exclusive access to *this. 00027 while (n_items_ == 0) { 00028 if (!wait(OK_TO_GET, 2000)) 00029 throw std::runtime_error("Buffer::get() timed out"); 00030 } 00031 int tmp = data_[--n_items_]; 00032 std::cerr << GET << tmp << " "; 00033 signal(OK_TO_PUT); 00034 return tmp; 00035 } 00036 00037 private: 00038 // Buffer capacity. 00039 enum { MAX = 3 }; 00040 // Names for conditions. 00041 enum { OK_TO_GET = 0, OK_TO_PUT = 1 }; /// conditions 00042 // Number of items in the buffer. 00043 int n_items_; 00044 // Actual store for items. 00045 int data_[MAX]; 00046 }; 00047 #endif
dvthread-0.13.4 | [11 December, 2009] |