1 // Copyright (C) 2001-2003
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)
9 #include <boost/utility.hpp>
10 #include <boost/thread/condition_variable.hpp>
11 #include <boost/thread/thread_only.hpp>
12 #include "../test/remove_error_code_unused_warning.hpp"
14 class bounded_buffer
: private boost::noncopyable
17 typedef boost::unique_lock
<boost::mutex
> lock
;
19 bounded_buffer(int n
) : boost::noncopyable(), begin(0), end(0), buffered(0), circular_buf(n
) { }
23 while (buffered
== circular_buf
.size())
24 buffer_not_full
.wait(lk
);
25 circular_buf
[end
] = m
;
26 end
= (end
+1) % circular_buf
.size();
28 buffer_not_empty
.notify_one();
33 buffer_not_empty
.wait(lk
);
34 int i
= circular_buf
[begin
];
35 begin
= (begin
+1) % circular_buf
.size();
37 buffer_not_full
.notify_one();
43 std::vector
<int>::size_type buffered
;
44 std::vector
<int> circular_buf
;
45 boost::condition_variable_any buffer_not_full
, buffer_not_empty
;
49 bounded_buffer
buf(2);
51 boost::mutex io_mutex
;
59 boost::unique_lock
<boost::mutex
> io_lock(io_mutex
);
60 std::cout
<< "sent: " << n
<< std::endl
;
73 boost::unique_lock
<boost::mutex
> io_lock(io_mutex
);
74 std::cout
<< "received: " << n
<< std::endl
;
76 } while (n
!= -1); // -1 indicates end of buffer
80 int main(int, char*[])
82 boost::thread
thrd1(&sender
);
83 boost::thread
thrd2(&receiver
);
84 boost::thread
thrd3(&receiver
);
85 boost::thread
thrd4(&receiver
);