-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJobQueue.h
103 lines (85 loc) · 1.58 KB
/
JobQueue.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
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
#pragma once
#include <functional>
#include <utility>
#include <memory>
using CallbackType = std::function<void()>;
using JobRef = shared_ptr<class Job>;
class Job
{
public:
Job(CallbackType&& callback) : _callback(std::move(callback))
{
}
template<typename T, typename Ret, typename... Args>
Job(shared_ptr<T> owner, Ret(T::* memFunc)(Args...), Args&&... args)
{
_callback = [owner, memFunc, args...]()
{
(owner.get()->*memFunc)(args...);
};
}
void Excute()
{
_callback();
}
private:
CallbackType _callback;
};
template<typename T>
class LockQueue
{
public:
void Push(T item)
{
WRITE_LOCK;
_items.push(item);
}
T Pop()
{
WRITE_LOCK;
if (_items.empty())
return T();
T ret = _items.front();
_items.pop();
return ret;
}
void PopAll(OUT std::vector<T>& items)
{
WRITE_LOCK;
while (T item = Pop())
items.push_back(item);
}
void Clear()
{
WRITE_LOCK;
_items = std::queue<T>();
}
private:
USE_LOCK;
std::queue<T> _items;
};
class JobQueue : public std::enable_shared_from_this<JobQueue>
{
public:
void DoAsync(CallbackType&& callback)
{
JobRef job = make_shared<Job>(std::move(callback));
Push(job);
}
template<typename T, typename Ret, typename... Args>
void DoAsync(Ret(T::* memFunc)(Args...), Args... args)
{
shared_ptr<T> owner = static_pointer_cast<T>(shared_from_this());
JobRef job = make_shared<Job>(owner, memFunc, std::forward<Args>(args)...);
Push(job);
}
void ClearJobs() { _jobQueue.Clear(); }
public:
void Push(JobRef job)
{
_jobQueue.Push(job);
}
void Execute();
private:
LockQueue<JobRef> _jobQueue;
};