forked from ChunelFeng/CGraph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUThreadSecondary.h
More file actions
128 lines (101 loc) · 3.06 KB
/
UThreadSecondary.h
File metadata and controls
128 lines (101 loc) · 3.06 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
/***************************
@Author: Chunel
@Contact: chunel@foxmail.com
@File: UThreadSecondary.h
@Time: 2021/7/8 11:02 下午
@Desc:
***************************/
#ifndef CGRAPH_UTHREADSECONDARY_H
#define CGRAPH_UTHREADSECONDARY_H
#include "UThreadBase.h"
CGRAPH_NAMESPACE_BEGIN
class UThreadSecondary : public UThreadBase {
public:
explicit UThreadSecondary() {
cur_ttl_ = 0;
type_ = CGRAPH_THREAD_TYPE_SECONDARY;
}
protected:
CStatus init() override {
CGRAPH_FUNCTION_BEGIN
CGRAPH_ASSERT_INIT(false)
CGRAPH_ASSERT_NOT_NULL(config_)
cur_ttl_ = config_->secondary_thread_ttl_;
is_init_ = true;
thread_ = std::thread(&UThreadSecondary::run, this);
setSchedParam();
CGRAPH_FUNCTION_END
}
/**
* 设置pool的信息
* @param poolTaskQueue
* @param poolPriorityTaskQueue
* @param config
* @return
*/
CStatus setThreadPoolInfo(UAtomicQueue<UTask>* poolTaskQueue,
UAtomicPriorityQueue<UTask>* poolPriorityTaskQueue,
UThreadPoolConfigPtr config) {
CGRAPH_FUNCTION_BEGIN
CGRAPH_ASSERT_INIT(false) // 初始化之前,设置参数
CGRAPH_ASSERT_NOT_NULL(poolTaskQueue, poolPriorityTaskQueue, config)
this->pool_task_queue_ = poolTaskQueue;
this->pool_priority_task_queue_ = poolPriorityTaskQueue;
this->config_ = config;
CGRAPH_FUNCTION_END
}
CStatus run() final {
CGRAPH_FUNCTION_BEGIN
CGRAPH_ASSERT_INIT(true)
loopProcess();
CGRAPH_FUNCTION_END
}
CVoid processTask() override {
UTask task;
if (popPoolTask(task)) {
runTask(task);
} else {
// 如果单次无法获取,则稍加等待
waitRunTask(config_->queue_emtpy_interval_);
}
}
CVoid processTasks() override {
UTaskArr tasks;
if (popPoolTask(tasks)) {
runTasks(tasks);
} else {
waitRunTask(config_->queue_emtpy_interval_);
}
}
/**
* 有等待的执行任务
* @param ms
* @return
* @notice 目的是降低cpu的占用率
*/
CVoid waitRunTask(CMSec ms) {
auto task = this->pool_task_queue_->popWithTimeout(ms);
if (nullptr != task) {
runTask(*task);
}
}
/**
* 判断本线程是否需要被自动释放
* @return
*/
bool freeze() {
if (likely(is_running_)) {
cur_ttl_++;
cur_ttl_ = std::min(cur_ttl_, config_->secondary_thread_ttl_);
} else {
cur_ttl_--; // 如果当前线程没有在执行,则ttl-1
}
return cur_ttl_ <= 0 && done_; // 必须是正在执行的线程,才可以被回收
}
private:
CSec cur_ttl_ = 0; // 当前最大生存周期
friend class UThreadPool;
};
using UThreadSecondaryPtr = UThreadSecondary *;
CGRAPH_NAMESPACE_END
#endif // CGRAPH_UTHREADSECONDARY_H