【Lua】题目小练4

-- 题目 :协程调度器

-- 要求:

-- 实现一个简单的"任务调度器",可以注册多个协程任务,并轮询执行,直到所有任务都完成。

Lua 复制代码
local Scheduler = {}
function Scheduler.new()
    local self = {
        corTable = {}
    }
    
    function self:addTask(func)
        local co = coroutine.create(func)
        table.insert(self.corTable,co)
    end

    function self:run()
        while #self.corTable > 0 do
            local i = 1
            while i <= #self.corTable do  
                local co = self.corTable[i]
                local status, val = coroutine.resume(co)
                if not status then
                    print("任务执行出错" .. tostring(co))
                    table.remove(self.corTable, i) --移除元素后,后面的协程会往前移动,因此不用进行i的累加
                elseif coroutine.status(co) == "dead" then
                    print("协程输出:"..tostring(val))
                    table.remove(self.corTable, i)
                else
                    i = i + 1
                end     
            end
        end
        print("所有的任务都已执行完成!")
    end

    return self
end

local s = Scheduler.new()

s:addTask(
    function()
        for i = 1, 3 do
            print("任务1:第"..i.."步")
            coroutine.yield("暂停1")
        end
    end
)

s:addTask(
    function()
        print("任务2")
    end
)

s:run()