-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue.hpp
49 lines (36 loc) · 1015 Bytes
/
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
#ifndef QUEUE_HPP
#define QUEUE_HPP
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
template< typename T, typename CONTAINER = std::queue< T > > class Queue {
mutable std::mutex m_mutex;
CONTAINER m_queue;
std::condition_variable m_cond;
public:
T dequeue( ) {
std::unique_lock< std::mutex > mlock( m_mutex );
while( m_queue.empty( ) ) {
m_cond.wait( mlock );
}
T item( std::move( m_queue.front( ) ) );
m_queue.pop( );
return item;
}
void enqueue( T item ) {
std::unique_lock< std::mutex > mlock( m_mutex );
m_queue.push( std::move( item ) );
mlock.unlock( );
m_cond.notify_one( );
}
typename CONTAINER::size_type size( ) const {
std::unique_lock< std::mutex > mlock( m_mutex );
return m_queue.size( );
}
void clear( ) {
std::unique_lock< std::mutex > mlock( m_mutex );
m_queue.clear( );
}
};
#endif