-
Notifications
You must be signed in to change notification settings - Fork 37
/
ThreadQueue.hpp
82 lines (70 loc) · 2.04 KB
/
ThreadQueue.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
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
#ifndef _THREADQUEUE_H_
#define _THREADQUEUE_H_
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
template <typename T, typename Container = std::queue<T>>
class ThreadQueue
{
public:
using container_type = Container;
using value_type = typename Container::value_type;
using reference = typename Container::reference;
using const_reference = typename Container::const_reference;
using size_type = typename Container::size_type;
using mutex_type = std::mutex;
using condition_variable_type = std::condition_variable;
private:
Container queue_;
mutex_type mutex_;
condition_variable_type cond_;
public:
ThreadQueue() = default;
ThreadQueue( const ThreadQueue & ) = delete;
ThreadQueue &operator=( const ThreadQueue & ) = delete;
void pop( reference elem )
{
std::unique_lock<mutex_type> lock( mutex_ );
cond_.wait( lock, [this]() { return !queue_.empty(); } );
elem = std::move( queue_.front() );
queue_.pop();
}
bool try_pop( reference elem )
{
std::unique_lock<mutex_type> lock( mutex_ );
if( queue_.empty() ) {
return false;
}
elem = std::move( queue_.front() );
queue_.pop();
return true;
}
bool empty() const
{
std::lock_guard<mutex_type> lock( mutex_ );
return queue_.empty();
}
size_type size() const
{
std::unique_lock<mutex_type> lock( mutex_ );
return queue_.size();
}
void push( const value_type &elem )
{
{
std::lock_guard<mutex_type> lock( mutex_ );
queue_.push( elem );
}
cond_.notify_one();
}
bool push( value_type &&elem )
{
{
std::lock_guard<mutex_type> lock( mutex_ );
queue_.push( std::move( elem ) );
}
cond_.notify_one();
}
};
#endif /* _THREADQUEUE_H_ */