协程非抢占式调度
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