FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
thread/tutorial/bounded_buffer.cpp at develop · boostorg/thread · GitHub
boostorg
thread
Repository navigation
Code
Issues
77
(77)
Pull requests
13
(13)
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
thread
/
tutorial
/
bounded_buffer.cpp
Copy path
More file actions
More file actions
Latest commit
History
History
History
69 lines (64 loc) · 1.7 KB
Breadcrumbs
thread
/
tutorial
/
bounded_buffer.cpp
Copy path
File metadata and controls
69 lines (64 loc) · 1.7 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
//
Copyright (C) 2001-2003
//
William E. Kempf
//
//
Distributed under the Boost Software License, Version 1.0. (See accompanying
//
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#
include
<
boost/thread/condition.hpp
>
#
include
<
boost/thread/mutex.hpp
>
#
include
<
boost/thread/thread.hpp
>
#
include
<
iostream
>
#
include
<
vector
>
class
bounded_buffer
:
private
boost
::noncopyable
{
public:
typedef
boost::mutex::scoped_lock lock;
bounded_buffer
(
int
n) : begin(
0
), end(
0
), buffered(
0
), circular_buf(n) { }
void
send
(
int
m) {
lock
lk
(monitor);
while
(buffered == circular_buf.
size
())
buffer_not_full.
wait
(lk);
circular_buf[end] = m;
end = (end+
1
) % circular_buf.
size
();
++buffered;
buffer_not_empty.
notify_one
();
}
int
receive
() {
lock
lk
(monitor);
while
(buffered ==
0
)
buffer_not_empty.
wait
(lk);
int
i = circular_buf[begin];
begin = (begin+
1
) % circular_buf.
size
();
--buffered;
buffer_not_full.
notify_one
();
return
i;
}
private:
int
begin, end, buffered;
std::vector<
int
> circular_buf;
boost::condition buffer_not_full, buffer_not_empty;
boost::mutex monitor;
};
bounded_buffer
buf
(
2
);
void
sender
() {
int
n =
0
;
while
(n <
100
) {
buf.
send
(n);
std::cout <<
"
sent:
"
<< n << std::endl;
++n;
}
buf.
send
(-
1
);
}
void
receiver
() {
int
n;
do
{
n = buf.
receive
();
std::cout <<
"
received:
"
<< n << std::endl;
}
while
(n != -
1
);
//
-1 indicates end of buffer
}
int
main
()
{
boost::thread
thrd1
(&sender);
boost::thread
thrd2
(&receiver);
thrd1.
join
();
thrd2.
join
();
}
Back
|
FazBrowse Home
|
New Git URL