Newer
Older
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
#include "sched.hh"
#include <list>
#include "mutex.hh"
#include <mutex>
#include "debug.hh"
namespace sched {
std::list<thread*> runqueue;
thread __thread * s_current;
elf::tls_data tls;
}
#include "arch-switch.hh"
namespace sched {
void schedule()
{
thread* p = thread::current();
if (!p->_waiting) {
return;
}
assert(!runqueue.empty());
thread* n = runqueue.front();
runqueue.pop_front();
assert(!n->_waiting);
n->_on_runqueue = false;
n->switch_to();
}
thread::thread(std::function<void ()> func, bool main)
: _func(func)
, _on_runqueue(true)
, _waiting(false)
{
if (!main) {
setup_tcb();
init_stack();
runqueue.push_back(this);
} else {
setup_tcb_main();
s_current = this;
func();
abort();
}
}
thread::~thread()
{
debug("thread dtor");
}
void thread::prepare_wait()
{
_waiting = true;
}
void thread::wake()
{
if (!_waiting) {
return;
}
_waiting = false;
if (!_on_runqueue) {
_on_runqueue = true;
runqueue.push_back(this);
schedule();
}
}
void thread::main()
{
_func();
}
thread* thread::current()
{
return sched::s_current;
}
void thread::wait()
{
if (!_waiting) {
return;
}
schedule();
}
void thread::stop_wait()
{
_waiting = false;
}
void init(elf::program& prog)
{
tls = prog.tls();
}
}