forked from andrew-d/cpplog
-
Notifications
You must be signed in to change notification settings - Fork 1
/
concurrent_queue.hpp
57 lines (47 loc) · 1.17 KB
/
concurrent_queue.hpp
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
#pragma once
#ifndef _CONCURRENT_QUEUE_H
#define _CONCURRENT_QUEUE_H
#include <queue>
#include <boost/thread.hpp>
template<typename Data>
class concurrent_queue
{
private:
std::queue<Data> the_queue;
mutable boost::mutex the_mutex;
boost::condition_variable the_condition_variable;
public:
void push(Data const& data)
{
boost::lock_guard<boost::mutex> lock(the_mutex);
the_queue.push(data);
the_condition_variable.notify_one();
}
bool empty() const
{
boost::lock_guard<boost::mutex> lock(the_mutex);
return the_queue.empty();
}
bool try_pop(Data& popped_value)
{
boost::unique_lock<boost::mutex> lock(the_mutex);
if( the_queue.empty() )
{
return false;
}
popped_value = the_queue.front();
the_queue.pop();
return true;
}
void wait_and_pop(Data& popped_value)
{
boost::unique_lock<boost::mutex> lock(the_mutex);
while( the_queue.empty() )
{
the_condition_variable.wait(lock);
}
popped_value = the_queue.front();
the_queue.pop();
}
};
#endif