-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsafe_queue.h
68 lines (56 loc) · 1.08 KB
/
safe_queue.h
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
// thread safe FIFO queue
//
#ifndef SAFE_QUEUE_H
#define SAFE_QUEUE_H
#include <assert.h>
#include <deque>
#include <condition_variable>
#include <mutex>
namespace mc //for memcache...
{
// to be used in producer/consumer kind of stuff
template< typename T >
struct safe_queue
{
typedef std::deque<T> queue;
typedef T value_type;
explicit safe_queue()
{}
//pass by value as it's intended for use with the move semantic
void push(value_type v)
{
std::unique_lock<std::mutex> lock(m_);
q_.push_back(std::move(v));
if (q_.size() == 1)
con_.notify_one();
}
value_type wait_next()
{
std::unique_lock<std::mutex> lock(m_);
while (true) {
if (q_.size()) {
return next();
}
con_.wait(lock);
}
throw 1; //to make compiler happy
}
bool is_empty()
{
std::unique_lock<std::mutex> lock(m_);
return q_.empty();
}
private:
std::mutex m_;
std::condition_variable con_;
queue q_;
value_type next()
{
assert(q_.size());
value_type v(std::move(q_.front()));
q_.pop_front();
return v;
}
};
}
#endif