-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy paththread_manager.lua
More file actions
106 lines (91 loc) · 2.34 KB
/
thread_manager.lua
File metadata and controls
106 lines (91 loc) · 2.34 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
local TM = { };
local ThreadManager = { StateFirstRun = 0, StateRunning = 1, StateSuspended = 2, StateWaiting = 3, threads = { } }
setmetatable(ThreadManager, { __index = TM });
function ThreadManager:Resume(name)
for i = 1, #self.threads do
if(self.threads[i]._name == name) then
if(self.threads[i]._state == self.StateFirstRun) then
self.threads[i]._state = self.StateRunning;
coroutine.resume(self.threads[i]._co, unpack(self.threads[i]._args));
elseif(self.threads[i]._state == self.StateSuspended) then
self.threads[i]._state = self.StateRunning;
coroutine.resume(self.threads[i]._co);
elseif(self.threads[i]._state == self.StateWaiting) then
if(eq.clock() >= self.threads[i]._wait_until) then
self.threads[i]._state = self.StateRunning;
coroutine.resume(self.threads[i]._co);
end
end
end
end
end
function ThreadManager:Create(name, f, ...)
table.insert(self.threads, {
_name = name,
_co = coroutine.create(f),
_args = {...},
_state = self.StateFirstRun,
_wait_until = 0.0
});
end
function ThreadManager:Yield(...)
local running = coroutine.running();
if(running == nil) then
return;
end
for i = 1, #self.threads do
if(self.threads[i]._co == running) then
self.threads[i]._state = self.StateSuspended;
coroutine.yield(...);
return;
end
end
coroutine.yield(...);
end
function ThreadManager:Wait(t, ...)
local running = coroutine.running();
if(running == nil) then
return;
end
for i = 1, #self.threads do
if(self.threads[i]._co == running) then
self.threads[i]._state = self.StateWaiting;
self.threads[i]._wait_until = eq.clock() + t;
coroutine.yield(...);
return;
end
end
coroutine.yield(...);
end
function ThreadManager:Stop()
local running = coroutine.running();
if(running == nil) then
return;
end
for i = 1, #self.threads do
if(self.threads[i]._co == running) then
table.remove(self.threads, i);
coroutine.yield();
return;
end
end
coroutine.yield();
end
function ThreadManager:Clear()
local running = coroutine.running();
self.threads = { };
if(running) then
coroutine.yield();
end
end
function ThreadManager:GarbageCollect()
if(#self.threads == 0) then
return;
end
for i = #self.threads, 1, -1 do
if(coroutine.status(self.threads[i]._co) == "dead") then
table.remove(self.threads, i);
end
end
end
return ThreadManager;