1 #include <boost/thread/thread.hpp>
2 #include <boost/thread/mutex.hpp>
3 #include <boost/thread/condition.hpp>
4 #include <iostream>
5 using namespace std;
6
7 const int BUF_SIZE = 10;
8 const int ITERS = 100;
9
10 boost::mutex io_mutex;
11 typedef boost::mutex::scoped_lock SCOPE_LOCK;
12
13 class buffer
14 {
15 public:
16 buffer():p(0),c(0),full(0){ }
17
18 void put(int m)
19 {
20 SCOPE_LOCK lock(mutex);
21 if(full == BUF_SIZE)
22 {
23 {
24 SCOPE_LOCK locl(io_mutex);
25 cout<<"Buffer is full.Wait..."<<endl;
26 }
27 while(full == BUF_SIZE)
28 {
29 cond.wait(lock);
30 }
31 }
32 buf[p] = m;
33 p = (p+1) % BUF_SIZE;
34 ++full;
35 cond.notify_one();
36 //cond.notify_all();
37 }
38
39 int get()
40 {
41 SCOPE_LOCK lock(mutex);
42 if(full == 0)
43 {
44 {
45 SCOPE_LOCK locl(io_mutex);
46 cout<<"Buffer is empty.Wait..."<<endl;
47 }
48 while(full == 0)
49 {
50 cond.wait(lock);
51 }
52 }
53
54 int i = buf[c];
55
56 c = (c+1) % BUF_SIZE;
57 --full;
58 cond.notify_one();
59 return i;
60 }
61
62
63 private:
64 boost::mutex mutex;
65 boost::condition cond;
66 unsigned int p,c,full;
67 int buf[BUF_SIZE];
68 };
69
70 buffer buf;
71
72 void writer()
73 {
74 for(int n = 0; n < ITERS;n++)
75 {
76 {
77 SCOPE_LOCK(io_mutex);
78 cout<<"sending:"<<n<<endl;
79 }
80 buf.put(n);
81 }
82 }
83
84 void reader()
85 {
86 for(int i = 0;i < ITERS;i++)
87 {
88 int n = buf.get();
89 {
90 SCOPE_LOCK lock(io_mutex);
91 cout<<"receive:"<<n<<endl;
92 }
93 }
94 }
95
96 int main(int argc, char const *argv[])
97 {
98 boost::thread t1(&reader);
99 boost::thread t2(&writer);
100 t1.join();
101 t2.join();
102
103 return 0;
104 }