forked from ChunelFeng/CGraph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUTask.h
More file actions
81 lines (62 loc) · 2 KB
/
UTask.h
File metadata and controls
81 lines (62 loc) · 2 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
/***************************
@Author: Chunel
@Contact: chunel@foxmail.com
@File: UTask.h
@Time: 2021/7/2 11:32 下午
@Desc:
***************************/
#ifndef CGRAPH_UTASK_H
#define CGRAPH_UTASK_H
#include <vector>
#include <memory>
#include <type_traits>
#include "../UThreadObject.h"
CGRAPH_NAMESPACE_BEGIN
class UTask : public UThreadObject {
struct TaskBased {
explicit TaskBased() = default;
virtual CVoid call() = 0;
virtual ~TaskBased() = default;
};
// 退化以获得实际类型,修改思路参考:https://github.com/ChunelFeng/CThreadPool/pull/3
template<typename F, typename T = typename std::decay<F>::type>
struct TaskDerided : TaskBased {
T func_;
explicit TaskDerided(F&& func) : func_(std::forward<F>(func)) {}
CVoid call() final { func_(); }
};
public:
template<typename F>
UTask(F&& func, int priority = 0)
: impl_(new TaskDerided<F>(std::forward<F>(func)))
, priority_(priority) {}
CVoid operator()() {
// impl_ 理论上不可能为空
impl_ ? impl_->call() : throw CException("UTask inner function is nullptr");
}
UTask() = default;
UTask(UTask&& task) noexcept:
impl_(std::move(task.impl_)),
priority_(task.priority_) {}
UTask &operator=(UTask&& task) noexcept {
impl_ = std::move(task.impl_);
priority_ = task.priority_;
return *this;
}
CBool operator>(const UTask& task) const {
return priority_ < task.priority_; // 新加入的,放到后面
}
CBool operator<(const UTask& task) const {
return priority_ >= task.priority_;
}
CGRAPH_NO_ALLOWED_COPY(UTask)
private:
std::unique_ptr<TaskBased> impl_ = nullptr;
int priority_ = 0; // 任务的优先级信息
};
using UTaskRef = UTask &;
using UTaskPtr = UTask *;
using UTaskArr = std::vector<UTask>;
using UTaskArrRef = std::vector<UTask> &;
CGRAPH_NAMESPACE_END
#endif //CGRAPH_UTASK_H