-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththreadSafeQueue.cpp
More file actions
91 lines (79 loc) · 2.16 KB
/
threadSafeQueue.cpp
File metadata and controls
91 lines (79 loc) · 2.16 KB
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
#include <condition_variable>
#include <memory>
#include <mutex>
#include <queue>
template<typename T>
class ThreadSafeQueue
{
public:
ThreadSafeQueue() = default;
ThreadSafeQueue( const ThreadSafeQueue& t_queue )
{
std::lock_guard<std::mutex> lock( t_queue.m_queue_mutex );
m_data_queue = t_queue.m_data_queue;
}
ThreadSafeQueue& operator=( const ThreadSafeQueue& ) = delete;
void push( const T& data )
{
std::lock_guard<std::mutex> lock( m_queue_mutex );
m_data_queue.push(data);
m_cond_var.notify_one();
}
void emplace( const T&& data )
{
std::lock_guard<std::mutex> lock( m_queue_mutex );
m_data_queue.emplace(data);
m_cond_var.notify_one();
}
void waitAndPop( T& value )
{
std::unique_lock<std::mutex> lock( m_queue_mutex );
m_cond_var.wait( lock, [this] () { return !m_data_queue.empty(); } );
value = m_data_queue.front();
m_data_queue.pop();
}
std::shared_ptr<T> waitAndPop()
{
std::unique_lock<std::mutex> lock( m_queue_mutex );
m_cond_var.wait( lock, [this] () { return !m_data_queue.empty(); } );
std::shared_ptr<T> data( std::make_shared<T>( m_data_queue.front() ) );
m_data_queue.pop();
return data;
}
bool tryPop( T& value )
{
std::lock_guard<std::mutex> lock( m_queue_mutex );
if( m_data_queue.empty() )
{
return false;
}
value = m_data_queue.front();
m_data_queue.pop();
return true;
}
std::shared_ptr<T> tryPop()
{
std::lock_guard<std::mutex> lock( m_queue_mutex );
if( m_data_queue.empty() )
{
return std::shared_ptr<T>();
}
std::shared_ptr<T> data( std::make_shared<T>(m_data_queue.front()) );
m_data_queue.pop();
return data;
}
bool empty() const
{
std::lock_guard<std::mutex> lock( m_queue_mutex );
return m_data_queue.empty();
}
size_t size() const
{
std::lock_guard<std::mutex> lock( m_queue_mutex );
return m_data_queue.size();
}
private:
std::queue<T> m_data_queue;
mutable std::mutex m_queue_mutex;
std::condition_variable m_cond_var;
};