-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcthread.lua
More file actions
372 lines (364 loc) · 11.1 KB
/
cthread.lua
File metadata and controls
372 lines (364 loc) · 11.1 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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
-- CThreads Module
-- cthread.lua - Coroutine Threads in Pure Lua
-- (c) 2025 Sibot
-- Licensed under the MIT License
local function coro(func)
return function(...)
local result = table.pack(func(...))
coroutine.yield()
return table.unpack(result, 1, result.n)
end
end
local cthread = {}
cthread.list = {}
cthread.queue = {}
cthread.sleeping = {}
local function _trim(s)
return (s:gsub("^%s+", ""):gsub("%s+$", ""))
end
local function _strip_comment(line)
return (line:gsub("%-%-.*$", ""))
end
local function _is_blank_or_comment(line)
local s = _trim(_strip_comment(line))
return s == ""
end
local function _is_func_start(s)
return s:match("^function%s") or s:match("^local%s+function%s") or s:match("=%s*function%s*%(")
end
local function _is_func_end(s)
return s == "end"
end
local function _is_control_head(s)
if s:match("^if%s") or s:match("^for%s") or s:match("^while%s") or s:match("^repeat%s*$") then
return true
end
if s == "do" or s == "else" or s:match("^elseif%s") or s:match("^until%s") then
return true
end
return false
end
local function _has_coronized_call(s)
if s:find("%f[%w_]print%f[^%w_]") or s:find("%f[%w_]sleep%f[^%w_]") then
return true
end
return false
end
local function _needs_injection(stmt)
local s = _trim(_strip_comment(stmt))
if s == "" then return false end
if _is_control_head(s) then return false end
if s:match("^return") or s:match("^break") or s == "end" then return false end
if _has_coronized_call(s) then return false end
return true
end
local function inject_yields(code)
local out = {}
local in_func = false
for rawline in (code.."\n"):gmatch("([^\r\n]*)\r?\n") do
local line = rawline
local s = _trim(_strip_comment(line))
if _is_func_start(s) then
table.insert(out, line)
if not s:find("end%s*$") then in_func = true end
elseif in_func then
table.insert(out, line)
if _is_func_end(s) then in_func = false end
else
if _is_blank_or_comment(line) or _is_control_head(s) or s == "end" then
table.insert(out, line)
else
local any_semicolon = line:find(";")
if any_semicolon then
local body = _strip_comment(line)
local first = true
for part in body:gmatch("([^;]+)") do
local stmt = _trim(part)
if stmt ~= "" then
table.insert(out, stmt)
if _needs_injection(stmt) then
table.insert(out, "sleep(0)")
end
end
first = false
end
else
table.insert(out, line)
if _needs_injection(line) then
table.insert(out, "sleep(0)")
end
end
end
end
end
return table.concat(out, "\n")
end
cthread.env = {
assert = coro(assert),
collectgarbage = coro(collectgarbage),
dofile = coro(dofile),
error = coro(error),
_G = _G,
getmetatable = coro(getmetatable),
ipairs = coro(ipairs),
load = coro(load),
loadfile = coro(loadfile),
next = coro(next),
pairs = coro(pairs),
pcall = coro(pcall),
print = coro(print),
rawequal = coro(rawequal),
rawget = coro(rawget),
rawlen = coro(rawlen),
rawset = coro(rawset),
require = coro(require),
select = coro(select),
setmetatable = coro(setmetatable),
tonumber = coro(tonumber),
tostring = coro(tostring),
type = coro(type),
xpcall = coro(xpcall),
table = {
concat = coro(table.concat),
insert = coro(table.insert),
move = coro(table.move),
pack = coro(table.pack),
remove = coro(table.remove),
sort = coro(table.sort),
unpack = coro(table.unpack),
},
math = {
abs = coro(math.abs),
acos = coro(math.acos),
asin = coro(math.asin),
atan = coro(math.atan),
ceil = coro(math.ceil),
cos = coro(math.cos),
deg = coro(math.deg),
exp = coro(math.exp),
floor = coro(math.floor),
fmod = coro(math.fmod),
huge = "inf",
log = coro(math.log),
max = coro(math.max),
min = coro(math.min),
modf = coro(math.modf),
pi = 3.14159265359,
rad = coro(math.rad),
random = coro(math.random),
randomseed= coro(math.randomseed),
sin = coro(math.sin),
sqrt = coro(math.sqrt),
tan = coro(math.tan),
tointeger = coro(math.tointeger),
type = coro(math.type),
ult = coro(math.ult),
},
string = {
byte = coro(string.byte),
char = coro(string.char),
dump = coro(string.dump),
find = coro(string.find),
format = coro(string.format),
gmatch = coro(string.gmatch),
gsub = coro(string.gsub),
len = coro(string.len),
lower = coro(string.lower),
match = coro(string.match),
pack = coro(string.pack),
packsize = coro(string.packsize),
rep = coro(string.rep),
reverse = coro(string.reverse),
sub = coro(string.sub),
unpack = coro(string.unpack),
upper = coro(string.upper),
},
utf8 = {
char = coro(utf8.char),
codepoint = coro(utf8.codepoint),
codes = coro(utf8.codes),
len = coro(utf8.len),
offset = coro(utf8.offset),
},
coroutine = {
close = coro(coroutine.close),
create = coro(coroutine.create),
isyieldable = coro(coroutine.isyieldable),
resume = coro(coroutine.resume),
running = coro(coroutine.running),
status = coro(coroutine.status),
wrap = coro(coroutine.wrap),
yield = coro(coroutine.yield),
},
debug = {
debug = coro(debug.debug),
gethook = coro(debug.gethook),
getinfo = coro(debug.getinfo),
getlocal = coro(debug.getlocal),
getmetatable = coro(debug.getmetatable),
getregistry = coro(debug.getregistry),
getupvalue = coro(debug.getupvalue),
getuservalue = coro(debug.getuservalue),
sethook = coro(debug.sethook),
setlocal = coro(debug.setlocal),
setmetatable = coro(debug.setmetatable),
setupvalue = coro(debug.setupvalue),
setuservalue = coro(debug.setuservalue),
traceback = coro(debug.traceback),
upvalueid = coro(debug.upvalueid),
upvaluejoin = coro(debug.upvaluejoin),
},
io = {
close = coro(io.close),
flush = coro(io.flush),
input = coro(io.input),
lines = coro(io.lines),
open = coro(io.open),
output = coro(io.output),
popen = coro(io.popen),
read = coro(io.read),
tmpfile = coro(io.tmpfile),
type = coro(io.type),
write = coro(io.write),
},
os = {
clock = coro(os.clock),
date = coro(os.date),
difftime = coro(os.difftime),
execute = coro(os.execute),
exit = coro(os.exit),
getenv = coro(os.getenv),
remove = coro(os.remove),
rename = coro(os.rename),
setlocale = coro(os.setlocale),
time = coro(os.time),
tmpname = coro(os.tmpname),
},
package = {
config = package.config,
cpath = package.cpath,
loaded = package.loaded,
loadlib = coro(package.loadlib),
path = package.path,
preload = package.preload,
searchers = package.searchers,
searchpath = coro(package.searchpath),
},
sleep = coro(function(t)
t = tonumber(t) or 0
if t <= 0 then
return coroutine.yield()
end
local target = os.clock() + t
local current = coroutine.running()
for name, co in pairs(cthread.list) do
if co == current then
cthread.sleeping[name] = target
return coroutine.yield()
end
end
end)
}
function cthread.new(name, code)
local transformed = inject_yields(code)
local chunk, err = load(transformed, name, "t", cthread.env)
if not chunk then error("CThread Load Error '"..name.."': "..err) end
cthread.list[name] = coroutine.create(chunk)
end
function cthread.push(name)
cthread.queue[#cthread.queue+1] = name
end
function cthread.tick()
local now = os.clock()
for name, wake in pairs(cthread.sleeping) do
if now >= wake then
cthread.queue[#cthread.queue+1] = name
cthread.sleeping[name] = nil
end
end
local q = cthread.queue
cthread.queue = {}
for i = 1, #q do
local name = q[i]
local co = cthread.list[name]
if co and coroutine.status(co) ~= "dead" then
local ok, res = coroutine.resume(co)
if not ok then
print("CThread Runtime Error: "..name..":"..tostring(res))
elseif coroutine.status(co) ~= "dead" then
cthread.queue[#cthread.queue+1] = name
end
end
q[i] = nil
end
end
function cthread.start()
while #cthread.queue > 0 do
cthread.tick()
end
end
cthread.mail = cthread.mail or {}
local _unpack = table.unpack
local function _current_thread_name()
local this = coroutine.running()
for name, co in pairs(cthread.list) do
if co == this then return name end
end
return "<?>"
end
local function _ensure_box(name)
local box = cthread.mail[name]
if not box then
box = {}
cthread.mail[name] = box
end
return box
end
cthread.env.send = function(dst, key, ...)
if type(dst) ~= "string" then error("send: dst must be a thread name (string)") end
local from = _current_thread_name()
local box = _ensure_box(dst)
box[#box+1] = { from = from, key = key, args = { ... } }
return true
end
cthread.env.collect = function(from, key)
local me = _current_thread_name()
local box = _ensure_box(me)
if #box == 0 then return nil end
for i, msg in ipairs(box) do
local ok_from = (from == nil) or (msg.from == from)
local ok_key = (key == nil) or (msg.key == key)
if ok_from and ok_key then
table.remove(box, i)
return msg.from, msg.key, _unpack(msg.args)
end
end
return nil
end
local function used(func, ...)
collectgarbage("collect")
local start = os.clock()
local result = table.pack(func(...))
cthread.start()
local finish = os.clock()
result.cpu = tonumber(("%.4f"):format(finish - start))
return result
end
cthread.env["cthread"] = {}
cthread.env.cthread["push"] = coro(cthread.push)
cthread.env.cthread["new"] = coro(cthread.new)
cthread.env.cthread["start"] = coro(cthread.start)
-- Example
local res = used(function()
cthread.new("ping", [=[
cthread.new("pong", [[ print(math.pi)
print(math.huge)
print(math.sin(21))]])
cthread.push("pong")
cthread.start()
]=])
cthread.push("ping")
cthread.start()
end)
print(res.cpu)
print(collectgarbage("count"))