Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: downloads/boost_1_33_1/libs/thread/example/condition.cpp @ 12

Last change on this file since 12 was 12, checked in by landauf, 17 years ago

added boost

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