-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCodeSnap-BlockingQueue.html
371 lines (342 loc) · 10.7 KB
/
CodeSnap-BlockingQueue.html
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
<!----------------------------------------------------------------------------
CodeSnap-BlockingQueue.htm
Published 19 Mar 2017
Jim Fawcett, CSE687 : Object Oriented Design, Summer 2017
Note:
- Markup characters in the text part, enclosed in <pre>...</pre> have to be
replaced with escape sequences, e.g., < becomes < and > becomes >
- Be careful that you don't replace genuine markup characters with escape
sequences, e.g., everything outside of the <pre>...</pre> section.
----------------------------------------------------------------------------->
<html>
<head>
<script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="js/CSE687-LectNav.js"></script>
<script type="text/javascript" src="js/Fallback.js"></script>
<link rel="stylesheet" href="css/TopLevelV2.css?v=1.0" />
<link rel="stylesheet" href="css/CourseSupplements.css?v=1.0" />
<link rel="stylesheet" href="css/Fallback.css?v=1.0" />
<script type="text/javascript" src="js/CustomMarkup.js"></script>
<link rel="stylesheet" href="css/CustomMarkup.css?v=1.0" />
<style>
body {
margin: 0px 20px 20px 20px;
color: black;
background-color: #eee;
font-family: Consolas;
font-weight: 600;
font-size: 110%;
}
.indent {
margin-left: 20px;
margin-right: 20px;
}
h3 {
margin-bottom: 15px; margin-top: 15px;
}
h4 {
margin-bottom: 5px;
margin-top: 3px;
}
hr {
margin-top: 20px;
}
</style>
<style>
div.readings {
padding: 10px 20px 15px 20px;
}
div.readings > ul {
padding: 0px;
margin: 0px 20px;
}
div.readings > ul > li {
padding: 0px;
margin: 0px;
}
div.readings > ul > li > h4 {
padding: 0px;
margin: 0px;
}
pre {
font-family:"courier new", courier, monospace;
font-size:large;
}
</style>
</head>
<body>
<a name="top"></a>
<!-- site navigation menu built with Javascript -->
<nav>
<div id="nav">
<div id="remove">
<hr />
<a href="TopNav.htm">Site Navigation with no Javascript</a>
<hr />
<br />
</div>
</div>
</nav>
<div id="pagenav">
<ul>
<li><a href="#top">T</a></li>
<li><a id="N" href="#top">N</a></li>
<li><a id="P" href="#top" prev>P</a></li>
<li><a href="#bottom">B</a></li>
</ul>
</div>
<!--<h3>
<a href="CodeSnap-BasicHttpProgService.IService.cs.htm">IService.cs</a>,
<a href="CodeSnap-BasicHttpProgService.Service.cs.htm">Service.cs</a>,
<a href="CodeSnap-BasicHttpProgService.ProgClient.cs.htm">ProgClient.cs</a>,
<a href="CodeSnap-BasicHttpProgService.ProgHost.cs.htm">ProgHost.cs</a>
</h3>-->
<div style="font-size:large; font-weight:bold; margin:20px;">
This code illustrates how Packages should be structured<br />
and is also a good example of a template class.<br />
We will find BlockingQueue to be very useful when writing multi-threaded code.
</div>
<hr />
<h3>Cpp11-BlockingQueue.h</h3>
<pre>
#ifndef CPP11_BLOCKINGQUEUE_H
#define CPP11_BLOCKINGQUEUE_H
///////////////////////////////////////////////////////////////
// Cpp11-BlockingQueue.h - Thread-safe Blocking Queue //
// ver 1.3 //
// Jim Fawcett, CSE687 - Object Oriented Design, Spring 2015 //
///////////////////////////////////////////////////////////////
/*
* Package Operations:
* -------------------
* This package contains one thread-safe class: BlockingQueue<T>.
* Its purpose is to support sending messages between threads.
* It is implemented using C++11 threading constructs including
* std::condition_variable and std::mutex. The underlying storage
* is provided by the non-thread-safe std::queue<T>.
*
* Required Files:
* ---------------
* Cpp11-BlockingQueue.h
*
* Build Process:
* --------------
* devenv Cpp11-BlockingQueue.sln /rebuild debug
*
* Maintenance History:
* --------------------
* ver 1.3 : 04 Mar 2016
* - changed behavior of front() to throw exception
* on empty queue.
* - added comment about std::unique_lock in deQ()
* ver 1.2 : 27 Feb 2016
* - added front();
* - added move ctor and move assignment
* - deleted copy ctor and copy assignment
* ver 1.1 : 26 Jan 2015
* - added copy constructor and assignment operator
* ver 1.0 : 03 Mar 2014
* - first release
*
*/
#include <condition_variable>
#include <mutex>
#include <thread>
#include <queue>
#include <string>
#include <iostream>
#include <sstream>
template <typename T>
class BlockingQueue {
public:
BlockingQueue() {}
BlockingQueue(BlockingQueue<T>&& bq);
BlockingQueue<T>& operator=(BlockingQueue<T>&& bq);
BlockingQueue(const BlockingQueue<T>&) = delete;
BlockingQueue<T>& operator=(const BlockingQueue<T>&) = delete;
T deQ();
void enQ(const T& t);
T& front();
void clear();
size_t size();
private:
std::queue<T> q_;
std::mutex mtx_;
std::condition_variable cv_;
};
//----< move constructor >---------------------------------------------
template<typename T>
BlockingQueue<T>::BlockingQueue(BlockingQueue<T>&& bq) // need to lock so can't initialize
{
std::lock_guard<std::mutex> l(mtx_);
q_ = bq.q_;
while (bq.q_.size() > 0) // clear bq
bq.q_.pop();
/* can't copy or move mutex or condition variable, so use default members */
}
//----< move assignment >----------------------------------------------
template<typename T>
BlockingQueue<T>& BlockingQueue<T>::operator=(BlockingQueue<T>&& bq)
{
if (this == &bq) return *this;
std::lock_guard<std::mutex> l(mtx_);
q_ = bq.q_;
while (bq.q_.size() > 0) // clear bq
bq.q_.pop();
/* can't move assign mutex or condition variable so use target's */
return *this;
}
//----< remove element from front of queue >---------------------------
template<typename T>
T BlockingQueue<T>::deQ()
{
std::unique_lock<std::mutex> l(mtx_);
/*
This lock type is required for use with condition variables.
The operating system needs to lock and unlock the mutex:
- when wait is called, below, the OS suspends waiting thread
and releases lock.
- when notify is called in enQ() the OS relocks the mutex,
resumes the waiting thread and sets the condition variable to
signaled state.
std::lock_quard does not have public lock and unlock functions.
*/
if(q_.size() > 0)
{
T temp = q_.front();
q_.pop();
return temp;
}
// may have spurious returns so loop on !condition
while (q_.size() == 0)
cv_.wait(l, [this] () { return q_.size() > 0; });
T temp = q_.front();
q_.pop();
return temp;
}
//----< push element onto back of queue >------------------------------
template<typename T>
void BlockingQueue<T>::enQ(const T& t)
{
{
std::unique_lock<std::mutex> l(mtx_);
q_.push(t);
}
cv_.notify_one();
}
//----< peek at next item to be popped >-------------------------------
template <typename T>
T& BlockingQueue<T>::front()
{
std::lock_guard<std::mutex> l(mtx_);
if(q_.size() > 0)
return q_.front();
throw std::exception("attempt to deQue empty queue");
}
//----< remove all elements from queue >-------------------------------
template <typename T>
void BlockingQueue<T>::clear()
{
std::lock_guard<std::mutex> l(mtx_);
while (q_.size() > 0)
q_.pop();
}
//----< return number of elements in queue >---------------------------
template<typename T>
size_t BlockingQueue<T>::size()
{
std::lock_guard<std::mutex> l(mtx_);
return q_.size();
}
#endif
</pre>
<h3>Cpp11-BlockingQueue.cpp</h3>
<pre>
///////////////////////////////////////////////////////////////
// Cpp11-BlockingQueue.cpp - Thread-safe Blocking Queue //
// ver 1.3 //
// Jim Fawcett, CSE687 - Object Oriented Design, Spring 2013 //
///////////////////////////////////////////////////////////////
#include <condition_variable>
#include <mutex>
#include <thread>
#include <queue>
#include <string>
#include <iostream>
#include <sstream>
#include "Cpp11-BlockingQueue.h"
#ifdef TEST_BLOCKINGQUEUE
std::mutex ioLock;
void test(BlockingQueue<std::string>* pQ)
{
std::string msg;
do
{
msg = pQ->deQ();
{
std::lock_guard<std::mutex> l(ioLock);
std::cout << "\n thread deQed " << msg.c_str();
}
std::this_thread::sleep_for(std::chrono::milliseconds(10));
} while(msg != "quit");
}
int main()
{
std::cout << "\n Demonstrating C++11 Blocking Queue";
std::cout << "\n ====================================";
BlockingQueue<std::string> q;
std::thread t(test, &q);
for(int i=0; i<15; ++i)
{
std::ostringstream temp;
temp << i;
std::string msg = std::string("msg#") + temp.str();
{
std::lock_guard<std::mutex> l(ioLock);
std::cout << "\n main enQing " << msg.c_str();
}
q.enQ(msg);
std::this_thread::sleep_for(std::chrono::milliseconds(3));
}
q.enQ("quit");
t.join();
std::cout << "\n";
std::cout << "\n Making move copy of BlockingQueue";
std::cout << "\n -----------------------------------";
std::string msg = "test";
q.enQ(msg);
std::cout << "\n before move:";
std::cout << "\n q.size() = " << q.size();
std::cout << "\n q.front() = " << q.front();
BlockingQueue<std::string> q2 = std::move(q); // move assignment
std::cout << "\n after move:";
std::cout << "\n q2.size() = " << q2.size();
std::cout << "\n q.size() = " << q.size();
std::cout << "\n q2 element = " << q2.deQ() << "\n";
std::cout << "\n Move assigning state of BlockingQueue";
std::cout << "\n ---------------------------------------";
BlockingQueue<std::string> q3;
q.enQ("test");
std::cout << "\n before move:";
std::cout << "\n q.size() = " << q.size();
std::cout << "\n q.front() = " << q.front();
q3 = std::move(q);
std::cout << "\n after move:";
std::cout << "\n q.size() = " << q.size();
std::cout << "\n q3.size() = " << q3.size();
std::cout << "\n q3 element = " << q3.deQ() << "\n";
std::cout << "\n\n";
}
#endif
</pre>
<!--<div class="photo">
<img src="pictures/CSTstrip.jpg" width="100%" />
</div>-->
<footer>
<hr />
<div style="position:absolute; left:35px;">CSE687 - Object Oriented Design Course Notes</div>
Jim Fawcett © copyright 2017
</footer>
<a name="bottom"></a>
</body>
</html>