-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscheduler.h
129 lines (107 loc) · 2.39 KB
/
scheduler.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
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
129
#ifndef __SYLAR_SCHEDULER_H__
#define __SYLAR_SCHEDULER_H__
#include "fiber.h"
#include "thread.h"
#include <memory.h>
#include <string>
#include <list>
#include <vector>
namespace sylar {
class Scheduler {
public:
typedef std::shared_ptr<Scheduler> ptr;
typedef Mutex MutexType;
Scheduler(size_t threads = 1, bool use_call = true, const std::string& name = "");
virtual ~Scheduler();
const std::string& getName() const { return m_name; }
static Scheduler* GetThis();
static Fiber* GetMainFiber();
void start();
void stop();
template<class FiberOrCb>
void scheduler(FiberOrCb fc, int thread = -1) {
bool need_tickle = false;
{
MutexType::Lock lock(m_mutex);
need_tickle = schedulerNoLock(fc, thread);
}
if(need_tickle) {
tickle();
}
}
template<class InputIterator>
void scheduler(InputIterator begin, InputIterator end) {
bool need_tickle = false;
{
MutexType::Lock lock(m_mutex);
while(begin != end) {
need_tickle = schedulerNoLock(&*begin, -1) || need_tickle;
++begin;
}
if(need_tickle) {
tickle();
}
}
}
std::ostream& dump(std::ostream& os);
protected:
virtual void tickle();
void run();
virtual bool stopping();
virtual void idle();
void setThis();
bool hasIdleThreads() { return m_idleThreadCount > 0; }
private:
template<class FiberOrCb>
bool schedulerNoLock(FiberOrCb fc, int thread) {
bool need_tickle = m_fibers.empty();
FiberAndThread ft(fc, thread);
if(ft.fiber || ft.thread) {
m_fibers.push_back(ft);
}
return need_tickle;
}
struct FiberAndThread {
Fiber::ptr fiber;
std::function<void()> cb;
int thread;
FiberAndThread(Fiber::ptr f, int thr)
:fiber(f), thread(thr){
}
FiberAndThread(Fiber::ptr* f, int thr)
:thread(thr){
fiber.swap(*f);
}
FiberAndThread(std::function<void()> f, int thr)
:cb(f), thread(thr){
}
FiberAndThread(std::function<void()>* f, int thr)
:thread(thr){
cb.swap(*f);
}
FiberAndThread()
:thread(-1) {
}
void reset() {
fiber = nullptr;
cb = nullptr;
thread = -1;
}
};
private:
std::string m_name;
MutexType m_mutex;
Fiber::ptr m_rootFiber;
std::vector<Thread::ptr> m_threads;
std::list<FiberAndThread> m_fibers;
protected:
std::vector<int> m_threadIds;
size_t m_threadCount = 0;
size_t m_activeThreadCount = 0;
size_t m_idleThreadCount = 0;
bool m_stopping = true;
bool m_autoStop = false;
int m_rootThread = 0;
};
}
#endif