示例工程 22-scheduling-and-tasks
22-scheduling-and-tasks/03-blocking-task/main.lua
-- @runtimes lua54 luajit
--- 演示:长计算阻塞其它任务(用顺序而非耗时断言)。
local M = {}
local function worker(name, busy)
return coroutine.create(function()
for i = 1, 2 do
if busy then
local sum = 0
for n = 1, 20000 do
sum = sum + n
end
assert(sum > 0)
end
coroutine.yield(name .. i)
end
end)
end
--- @return table { order = table }
function M.run(log)
log = log or print
local queue = { worker("slow", true), worker("fast", false) }
local order = {}
while #queue > 0 do
local co = table.remove(queue, 1)
local ok, value = coroutine.resume(co)
assert(ok, value)
if coroutine.status(co) ~= "dead" then
queue[#queue + 1] = co
end
order[#order + 1] = value
end
log(("order=%s"):format(table.concat(order, ",")))
return { order = order }
end
if not ... then
M.run()
end
return M