-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path12-2.cpp
59 lines (48 loc) · 1.28 KB
/
12-2.cpp
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
#include <iostream>
#include <boost/thread/thread.hpp>
#include <string>
// A simple queue class; don't do this, use std::queue
template<typename T>
class Queue {
public:
Queue( ) {}
~Queue( ) {}
void enqueue(const T& x) {
// Lock the mutex for this queue
boost::mutex::scoped_lock lock(mutex_);
list_.push_back(x);
// A scoped_lock is automatically destroyed (and thus unlocked)
// when it goes out of scope
}
T dequeue( ) {
boost::mutex::scoped_lock lock(mutex_);
if (list_.empty( ))
throw "empty!"; // This leaves the current scope, so the
T tmp = list_.front( ); // lock is released
list_.pop_front( );
return(tmp);
} // Again: when scope ends, mutex_ is unlocked
private:
std::list<T> list_;
boost::mutex mutex_;
};
Queue<std::string> queueOfStrings;
void sendSomething( ) {
std::string s;
for (int i = 0; i < 10; ++i) {
queueOfStrings.enqueue("Cyrus");
}
}
void recvSomething( ) {
std::string s;
for (int i = 0; i < 10; ++i) {
try {s = queueOfStrings.dequeue( );}
catch(...) {}
}
}
int main( ) {
boost::thread thr1(sendSomething);
boost::thread thr2(recvSomething);
thr1.join( );
thr2.join( );
}