協程是 Lua 實現協作式多任務的核心機制。不同於線程的搶佔式調度,協程由程序員顯式控制暫停 (yield) 與恢復 (resume),無鎖、無競態、極低開銷,極適合高併發網絡服務、遊戲邏輯幀、異步流程控制、迭代器生成等場景。本文系統講解協程原理、完整 API、經典模式、錯誤處理與實戰案例。
coroutine.create(f) 創建,類型 "thread"。擁有獨立棧、指令指針、局部變量環境。"suspended" (掛起/就緒)、"running" (正在運行)、"dead" (結束/出錯)。coroutine.status(co) 查詢。resume(co, ...) → 傳參給協程(首次作為函數參數,後續作為 yield 返回值)。yield(...) → 返回值給 resume 調用者,同時掛起協程。create → resume (運行) → yield (掛起) → resume ... → 函數返回/報錯 → dead。dead 協程不可再 resume。| 函數 | 簽名 | 說明 |
|---|---|---|
create | coroutine.create(f) | 創建協程,返回 thread 對象。f 為函數。 |
resume | coroutine.resume(co, ...) | 啟動/恢復協程。返回 true, ... (成功) 或 false, errMsg (錯誤)。 |
yield | coroutine.yield(...) | 掛起當前協程,返回值給對應的 resume。只能在協程主函數或其調用鏈中調用(不能在 C 函數/元方法中直接 yield,除非用 C API lua_yieldk)。 |
status | coroutine.status(co) | 返回狀態字符串。 |
wrap | coroutine.wrap(f) | 創建協程並返回一個函數,調用該函數相當於 resume。錯誤直接拋出(無錯誤碼返回),適合簡單場景。 |
running | coroutine.running() | 返回當前運行協程對象 (5.1) 或對象+是否主線程 (5.2+)。 |
isyieldable | coroutine.isyieldable() | 5.2+ 判斷當前上下文是否可 yield。 |
local function producer()
return coroutine.create(function()
for i = 1, 5 do
coroutine.yield(i) -- 生產數據
end
end)
end
local function consumer(prod)
while true do
local ok, val = coroutine.resume(prod)
if not ok then error(val) end
if not val then break end -- 生產結束
print("Consumed:", val)
end
end
consumer(producer())
-- 輸出: Consumed: 1 ... 5
local function filter(pred, src)
return coroutine.create(function()
while true do
local ok, val = coroutine.resume(src)
if not ok then error(val) end
if not val then return end
if pred(val) then coroutine.yield(val) end
end
end)
end
local src = producer()
local even = filter(function(x) return x%2==0 end, src)
local sq = filter(function(x) return x*x end, even) -- 鏈式
while true do
local ok, val = coroutine.resume(sq)
if not ok then error(val) end
if not val then break end
print(val) -- 4, 16
end
模擬 async/await:
local function async_op(delay, value)
return coroutine.create(function()
-- 模擬異步 IO:註冊定時器,yield 釋放控制權
-- 這裡簡化為 yield 等待外部驅動
coroutine.yield("WAIT", delay, value)
end)
end
-- 事件循環調度器(簡化版)
local function run(tasks)
local timers = {}
while #tasks > 0 do
local co = table.remove(tasks, 1)
local ok, typ, arg1, arg2 = coroutine.resume(co)
if not ok then print("Error:", typ) end
if typ == "WAIT" then
-- 實際應放入定時器堆,這裡直接重新排隊演示
table.insert(tasks, co)
elseif coroutine.status(co) ~= "dead" then
table.insert(tasks, co)
end
end
end
local function tree_iter(root)
local co = coroutine.create(function(node)
local function traverse(n)
if not n then return end
coroutine.yield(n.value)
for _, child in ipairs(n.children) do traverse(child) end
end
traverse(node)
end)
return function()
local ok, val = coroutine.resume(co)
return ok and val or nil
end
end
-- 使用
for v in tree_iter(root_node) do print(v) end
local ok, err = coroutine.resume(co)。ok=false 時 err 為錯誤對象(字符串/錯誤對象)。不會拋出異常,需手動檢查。debug.traceback(co) 獲取協程棧跡。coroutine.running() 獲取當前協程。error() 會導致協程 dead,下次 resume 返回 false, err。外層可捕獲並決定重試/記錄/終止。local http = require "socket.http"
local ltn12 = require "ltn12"
local function download(url, sink)
return coroutine.create(function()
local _, code, headers, status = http.request{
url = url,
sink = ltn12.sink.table(sink),
method = "GET"
}
coroutine.yield(code, table.concat(sink))
end)
end
local function limited_concurrent(urls, limit)
local running, queue = 0, {}
local function start_next()
while running < limit and #urls > 0 do
local url = table.remove(urls, 1)
local sink = {}
local co = download(url, sink)
running = running + 1
local function check()
local ok, code, body = coroutine.resume(co)
running = running - 1
if ok then
print(string.format("[%d] %s: %d bytes", code, url, #body))
else
print("Failed:", url, code)
end
start_next()
end
-- 首次 resume 啟動請求(實際需異步 IO 回調驅動,此處簡化同步調用)
check()
end
end
start_next()
end
limited_concurrent({
"https://example.com/1",
"https://example.com/2",
-- ...
}, 3)
| 特性 | 協程 | OS 線程 | 異步回調 |
|---|---|---|---|
| 調度 | 用戶態協作式 | 內核態搶佔式 | 事件循環協作式 |
| 棧大小 | ~KB (可增長) | ~MB (固定) | 單棧 (事件循環) |
| 上下文切換 | 極快 (指針切換) | 慢 (系統調用) | 快 (函數調用) |
| 併發規模 | 萬級輕鬆 | 百級受限 | 萬級 (單線程) |
| 共享狀態 | 需自行同步 (較少) | 需鎖/CAS | 單線程無鎖 |
| 阻塞 IO | 需 yield 讓出 (配合非阻塞 IO) | 自然阻塞 | 禁止 (回調地獄) |
| 調試難度 | 中 (棧跨 yield 斷裂) | 高 (競態/死鎖) | 高 (回調分散) |
coroutine.wrap 包裝、或升級 Lua 5.2+ 使用 lua_yieldk 續體、或將邏輯移至 Lua 層 yield。resume 參數 → 協程函數參數 (首次) / yield 返回值 (後續)。yield 返回值 → resume 返回值。數量不固定,按位置對應。status=="dead" 時不可 resume。需重新 create。_G。用 local、模塊、setfenv(5.1)/_ENV(5.2+) 隔離。Lua 協程以極簡 API 實現了強大的控制流抽象。它不是線程,而是「可暫停的函數」。掌握 create/resume/yield 三元組,理解雙向數據流與狀態機本質,你就能構建高併發網關、遊戲幀邏輯、複雜解析器、優雅的異步流程控制。記住:協程的藝術在於「在恰當的時機 yield,把控制權交還調度器」。