前置知识: Lua

协程非抢占式调度

00:00
1 min Advanced 2026/6/14

Lua协程非抢占式调度详解。

1. 协程基础

local co = coroutine.create(function()
    print("step 1")
    coroutine.yield()
    print("step 2")
end)

coroutine.resume(co)  -- step 1
coroutine.resume(co)  -- step 2

2. 非抢占式调度

Lua 协程协作式任务,必须显式 yield 才能切换

--  死循环,其他协程无法运行
local co = coroutine.create(function()
    while true do
        -- 没有 yield,永远不释放控制权
    end
end)

--  定期 yield
local co = coroutine.create(function()
    for i = 1, 1000000 do
        process(i)
        if i % 1000 == 0 then
            coroutine.yield()  -- 每 1000 次让出
        end
    end
end)

3. 协程状态

状态说明
suspended挂起(初始yield 后)
running
normal恢复其他协程
dead执行完毕

4. 生产者-消费者

function producer()
    return coroutine.create(function()
        while true do
            local value = io.read()
            coroutine.yield(value)
        end
    end)
end

function consumer(prod)
    while true do
        local _, value = coroutine.resume(prod)
        if not value then break end
        print("Consumed:", value)
    end
end

知识检测

学习进度

-- 已学文档
--% 知识覆盖率

学习推荐

专注模式