forked from caozhiyi/foundation
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTaskQueue.h
55 lines (45 loc) · 1.23 KB
/
TaskQueue.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
#ifndef HEADER_TASKQUEUE
#define HEADER_TASKQUEUE
#include <list>
#include <mutex>
#include <condition_variable>
template<typename T>
class CTaskQueue {
public:
CTaskQueue(int size = -1) :_list_size(size > 0 ? size : INT_MAX) {
}
~CTaskQueue() {
}
void Push(const T& element) {
std::unique_lock<std::mutex> lock(_block_mutex);
_full_notify.wait(_block_mutex, [this]() {return this->_block_queue.size() < this->_list_size; });
_block_queue.push_front(element);
_empty_notify.notify_all();
}
T Pop() {
std::unique_lock<std::mutex> lock(_block_mutex);
_empty_notify.wait(_block_mutex, [this]() {return !this->_block_queue.empty(); });
T ret = std::move(_block_queue.back());
_block_queue.pop_back();
_full_notify.notify_all();
return std::move(ret);
}
void Clear(bool notify = true) {
std::unique_lock<std::mutex> lock(_block_mutex);
while (!_block_queue.empty()) {
_block_queue.pop_front();
_full_notify.notify_one();
}
}
int Size() {
std::unique_lock<std::mutex> lock(_block_mutex);
return _block_queue.size();
}
private:
int _list_size;
std::list<T> _block_queue;
std::mutex _block_mutex;
std::condition_variable_any _empty_notify;
std::condition_variable_any _full_notify;
};
#endif