【Lua】题目小练4
-- 题目 :协程调度器
-- 要求:
-- 实现一个简单的“任务调度器”,可以注册多个协程任务,并轮询执行,直到所有任务都完成。
local Scheduler = {} function Scheduler.new()local self = {corTable = {}}function self:addTask(func)local co = coroutine.create(func)table.insert(self.corTable,co)endfunction self:run()while #self.corTable > 0 dolocal i = 1while i <= #self.corTable do local co = self.corTable[i]local status, val = coroutine.resume(co)if not status thenprint("任务执行出错" .. tostring(co))table.remove(self.corTable, i) --移除元素后,后面的协程会往前移动,因此不用进行i的累加elseif coroutine.status(co) == "dead" thenprint("协程输出:"..tostring(val))table.remove(self.corTable, i)elsei = i + 1end endendprint("所有的任务都已执行完成!")endreturn self endlocal s = Scheduler.new()s:addTask(function()for i = 1, 3 doprint("任务1:第"..i.."步")coroutine.yield("暂停1")endend )s:addTask(function()print("任务2")end )s:run()