1 // Copyright (C) 2001-2003 2 // William E. Kempf 3 // 4 // Distributed under the Boost Software License, Version 1.0. (See accompanying 5 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) 6 7 #include <boost/thread/condition.hpp> 8 #include <boost/thread/mutex.hpp> 9 #include <boost/thread/thread.hpp> 10 #include <iostream> 11 #include <vector> 12 13 class bounded_buffer : private boost::noncopyable 14 { 15 public: 16 typedef boost::mutex::scoped_lock lock; bounded_buffer(int n)17 bounded_buffer(int n) : begin(0), end(0), buffered(0), circular_buf(n) { } send(int m)18 void send (int m) { 19 lock lk(monitor); 20 while (buffered == circular_buf.size()) 21 buffer_not_full.wait(lk); 22 circular_buf[end] = m; 23 end = (end+1) % circular_buf.size(); 24 ++buffered; 25 buffer_not_empty.notify_one(); 26 } receive()27 int receive() { 28 lock lk(monitor); 29 while (buffered == 0) 30 buffer_not_empty.wait(lk); 31 int i = circular_buf[begin]; 32 begin = (begin+1) % circular_buf.size(); 33 --buffered; 34 buffer_not_full.notify_one(); 35 return i; 36 } 37 private: 38 int begin, end, buffered; 39 std::vector<int> circular_buf; 40 boost::condition buffer_not_full, buffer_not_empty; 41 boost::mutex monitor; 42 }; 43 bounded_buffer buf(2); 44 sender()45void sender() { 46 int n = 0; 47 while (n < 100) { 48 buf.send(n); 49 std::cout << "sent: " << n << std::endl; 50 ++n; 51 } 52 buf.send(-1); 53 } 54 receiver()55void receiver() { 56 int n; 57 do { 58 n = buf.receive(); 59 std::cout << "received: " << n << std::endl; 60 } while (n != -1); // -1 indicates end of buffer 61 } 62 main()63int main() 64 { 65 boost::thread thrd1(&sender); 66 boost::thread thrd2(&receiver); 67 thrd1.join(); 68 thrd2.join(); 69 } 70