forked from ChunelFeng/CGraph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUAtomicPriorityQueue.h
More file actions
94 lines (76 loc) · 2.21 KB
/
UAtomicPriorityQueue.h
File metadata and controls
94 lines (76 loc) · 2.21 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
92
93
94
/***************************
@Author: Chunel
@Contact: chunel@foxmail.com
@File: UAtomicPriorityQueue.h
@Time: 2022/10/1 21:40
@Desc: 线程安全的优先队列。因为 priority_queue和queue的弹出方式不一致,故暂时不做合并
***************************/
#ifndef CGRAPH_UATOMICPRIORITYQUEUE_H
#define CGRAPH_UATOMICPRIORITYQUEUE_H
#include <queue>
#include "UQueueObject.h"
CGRAPH_NAMESPACE_BEGIN
template<typename T>
class UAtomicPriorityQueue : public UQueueObject {
public:
UAtomicPriorityQueue() = default;
/**
* 尝试弹出
* @param value
* @return
*/
CBool tryPop(T& value) {
CBool result = false;
if (mutex_.try_lock()) {
if (!priority_queue_.empty()) {
value = std::move(*priority_queue_.top());
priority_queue_.pop();
result = true;
}
mutex_.unlock();
}
return result;
}
/**
* 尝试弹出多个任务
* @param values
* @param maxPoolBatchSize
* @return
*/
CBool tryPop(std::vector<T>& values, int maxPoolBatchSize) {
CBool result = false;
if (mutex_.try_lock()) {
while (!priority_queue_.empty() && maxPoolBatchSize-- > 0) {
values.emplace_back(std::move(*priority_queue_.top()));
priority_queue_.pop();
result = true;
}
mutex_.unlock();
}
return result;
}
/**
* 传入数据
* @param value
* @param priority 任务优先级,数字排序
* @return
*/
CVoid push(T&& value, int priority) {
std::unique_ptr<T> task(c_make_unique<T>(std::move(value), priority));
CGRAPH_LOCK_GUARD lk(mutex_);
priority_queue_.push(std::move(task));
}
/**
* 判定队列是否为空
* @return
*/
CBool empty() {
CGRAPH_LOCK_GUARD lk(mutex_);
return priority_queue_.empty();
}
CGRAPH_NO_ALLOWED_COPY(UAtomicPriorityQueue)
private:
std::priority_queue<std::unique_ptr<T> > priority_queue_; // 优先队列信息,根据重要级别决定先后执行顺序
};
CGRAPH_NAMESPACE_END
#endif //CGRAPH_UATOMICPRIORITYQUEUE_H