| 1 | // Copyright (C) 2001-2003 |
|---|
| 2 | // William E. Kempf |
|---|
| 3 | // |
|---|
| 4 | // Permission to use, copy, modify, distribute and sell this software |
|---|
| 5 | // and its documentation for any purpose is hereby granted without fee, |
|---|
| 6 | // provided that the above copyright notice appear in all copies and |
|---|
| 7 | // that both that copyright notice and this permission notice appear |
|---|
| 8 | // in supporting documentation. William E. Kempf makes no representations |
|---|
| 9 | // about the suitability of this software for any purpose. |
|---|
| 10 | // It is provided "as is" without express or implied warranty. |
|---|
| 11 | |
|---|
| 12 | #include <boost/thread/condition.hpp> |
|---|
| 13 | #include <boost/thread/mutex.hpp> |
|---|
| 14 | #include <boost/thread/thread.hpp> |
|---|
| 15 | #include <iostream> |
|---|
| 16 | #include <vector> |
|---|
| 17 | |
|---|
| 18 | class bounded_buffer : private boost::noncopyable |
|---|
| 19 | { |
|---|
| 20 | public: |
|---|
| 21 | typedef boost::mutex::scoped_lock lock; |
|---|
| 22 | bounded_buffer(int n) : begin(0), end(0), buffered(0), circular_buf(n) { } |
|---|
| 23 | void send (int m) { |
|---|
| 24 | lock lk(monitor); |
|---|
| 25 | while (buffered == circular_buf.size()) |
|---|
| 26 | buffer_not_full.wait(lk); |
|---|
| 27 | circular_buf[end] = m; |
|---|
| 28 | end = (end+1) % circular_buf.size(); |
|---|
| 29 | ++buffered; |
|---|
| 30 | buffer_not_empty.notify_one(); |
|---|
| 31 | } |
|---|
| 32 | int receive() { |
|---|
| 33 | lock lk(monitor); |
|---|
| 34 | while (buffered == 0) |
|---|
| 35 | buffer_not_empty.wait(lk); |
|---|
| 36 | int i = circular_buf[begin]; |
|---|
| 37 | begin = (begin+1) % circular_buf.size(); |
|---|
| 38 | --buffered; |
|---|
| 39 | buffer_not_full.notify_one(); |
|---|
| 40 | return i; |
|---|
| 41 | } |
|---|
| 42 | private: |
|---|
| 43 | int begin, end, buffered; |
|---|
| 44 | std::vector<int> circular_buf; |
|---|
| 45 | boost::condition buffer_not_full, buffer_not_empty; |
|---|
| 46 | boost::mutex monitor; |
|---|
| 47 | }; |
|---|
| 48 | bounded_buffer buf(2); |
|---|
| 49 | |
|---|
| 50 | void sender() { |
|---|
| 51 | int n = 0; |
|---|
| 52 | while (n < 100) { |
|---|
| 53 | buf.send(n); |
|---|
| 54 | std::cout << "sent: " << n << std::endl; |
|---|
| 55 | ++n; |
|---|
| 56 | } |
|---|
| 57 | buf.send(-1); |
|---|
| 58 | } |
|---|
| 59 | |
|---|
| 60 | void receiver() { |
|---|
| 61 | int n; |
|---|
| 62 | do { |
|---|
| 63 | n = buf.receive(); |
|---|
| 64 | std::cout << "received: " << n << std::endl; |
|---|
| 65 | } while (n != -1); // -1 indicates end of buffer |
|---|
| 66 | } |
|---|
| 67 | |
|---|
| 68 | int main() |
|---|
| 69 | { |
|---|
| 70 | boost::thread thrd1(&sender); |
|---|
| 71 | boost::thread thrd2(&receiver); |
|---|
| 72 | thrd1.join(); |
|---|
| 73 | thrd2.join(); |
|---|
| 74 | } |
|---|