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 <iostream> |
---|
8 | #include <vector> |
---|
9 | #include <boost/utility.hpp> |
---|
10 | #include <boost/thread/condition.hpp> |
---|
11 | #include <boost/thread/thread.hpp> |
---|
12 | |
---|
13 | class bounded_buffer : private boost::noncopyable |
---|
14 | { |
---|
15 | public: |
---|
16 | typedef boost::mutex::scoped_lock lock; |
---|
17 | |
---|
18 | bounded_buffer(int n) : begin(0), end(0), buffered(0), circular_buf(n) { } |
---|
19 | |
---|
20 | void send (int m) { |
---|
21 | lock lk(monitor); |
---|
22 | while (buffered == circular_buf.size()) |
---|
23 | buffer_not_full.wait(lk); |
---|
24 | circular_buf[end] = m; |
---|
25 | end = (end+1) % circular_buf.size(); |
---|
26 | ++buffered; |
---|
27 | buffer_not_empty.notify_one(); |
---|
28 | } |
---|
29 | int receive() { |
---|
30 | lock lk(monitor); |
---|
31 | while (buffered == 0) |
---|
32 | buffer_not_empty.wait(lk); |
---|
33 | int i = circular_buf[begin]; |
---|
34 | begin = (begin+1) % circular_buf.size(); |
---|
35 | --buffered; |
---|
36 | buffer_not_full.notify_one(); |
---|
37 | return i; |
---|
38 | } |
---|
39 | |
---|
40 | private: |
---|
41 | int begin, end, buffered; |
---|
42 | std::vector<int> circular_buf; |
---|
43 | boost::condition buffer_not_full, buffer_not_empty; |
---|
44 | boost::mutex monitor; |
---|
45 | }; |
---|
46 | |
---|
47 | bounded_buffer buf(2); |
---|
48 | |
---|
49 | void sender() { |
---|
50 | int n = 0; |
---|
51 | while (n < 100) { |
---|
52 | buf.send(n); |
---|
53 | std::cout << "sent: " << n << std::endl; |
---|
54 | ++n; |
---|
55 | } |
---|
56 | buf.send(-1); |
---|
57 | } |
---|
58 | |
---|
59 | void receiver() { |
---|
60 | int n; |
---|
61 | do { |
---|
62 | n = buf.receive(); |
---|
63 | std::cout << "received: " << n << std::endl; |
---|
64 | } while (n != -1); // -1 indicates end of buffer |
---|
65 | } |
---|
66 | |
---|
67 | int main(int, char*[]) |
---|
68 | { |
---|
69 | boost::thread thrd1(&sender); |
---|
70 | boost::thread thrd2(&receiver); |
---|
71 | thrd1.join(); |
---|
72 | thrd2.join(); |
---|
73 | return 0; |
---|
74 | } |
---|