bounded_buffer.cpp 1.7 KB

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