萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Lua 協程編程完全指南:原理、API、模式與實戰應用

協程是 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。

二、 完整 API 速查表

函數簽名說明
createcoroutine.create(f)創建協程,返回 thread 對象。f 為函數。
resumecoroutine.resume(co, ...)啟動/恢復協程。返回 true, ... (成功) 或 false, errMsg (錯誤)。
yieldcoroutine.yield(...)掛起當前協程,返回值給對應的 resume。只能在協程主函數或其調用鏈中調用(不能在 C 函數/元方法中直接 yield,除非用 C API lua_yieldk)。
statuscoroutine.status(co)返回狀態字符串。
wrapcoroutine.wrap(f)創建協程並返回一個函數,調用該函數相當於 resume。錯誤直接拋出(無錯誤碼返回),適合簡單場景。
runningcoroutine.running()返回當前運行協程對象 (5.1) 或對象+是否主線程 (5.2+)。
isyieldablecoroutine.isyieldable()5.2+ 判斷當前上下文是否可 yield。

三、 經典交互模式詳解

1. 生產者-消費者模式(管道流)

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

2. 過濾器/管道鏈

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

3. 非阻塞異步等待(事件循環核心)

模擬 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

4. 迭代器生成器(無狀態遍歷複雜結構)

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

四、 錯誤處理與調試

  • resume 返回錯誤:local ok, err = coroutine.resume(co)。ok=false 時 err 為錯誤對象(字符串/錯誤對象)。不會拋出異常,需手動檢查。
  • 調試輔助:debug.traceback(co) 獲取協程棧跡。coroutine.running() 獲取當前協程。
  • 錯誤傳播:協程內部 error() 會導致協程 dead,下次 resume 返回 false, err。外層可捕獲並決定重試/記錄/終止。

五、 實戰案例:簡易 HTTP 下載器併發控制

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)

六、 協程 vs 線程 vs 異步回調

特性協程OS 線程異步回調
調度用戶態協作式內核態搶佔式事件循環協作式
棧大小~KB (可增長)~MB (固定)單棧 (事件循環)
上下文切換極快 (指針切換)慢 (系統調用)快 (函數調用)
併發規模萬級輕鬆百級受限萬級 (單線程)
共享狀態需自行同步 (較少)需鎖/CAS單線程無鎖
阻塞 IO需 yield 讓出 (配合非阻塞 IO)自然阻塞禁止 (回調地獄)
調試難度中 (棧跨 yield 斷裂)高 (競態/死鎖)高 (回調分散)

七、 避坑指南

  1. 不能在 C 函數/元方法中直接 yield (Lua 5.1)。解決:用 coroutine.wrap 包裝、或升級 Lua 5.2+ 使用 lua_yieldk 續體、或將邏輯移至 Lua 層 yield。
  2. 傳遞參數數量不匹配:resume 參數 → 協程函數參數 (首次) / yield 返回值 (後續)。yield 返回值 → resume 返回值。數量不固定,按位置對應。
  3. 死協程重用:status=="dead" 時不可 resume。需重新 create。
  4. 全局變量污染:協程間共享 _G。用 local、模塊、setfenv(5.1)/_ENV(5.2+) 隔離。

結語

Lua 協程以極簡 API 實現了強大的控制流抽象。它不是線程,而是「可暫停的函數」。掌握 create/resume/yield 三元組,理解雙向數據流與狀態機本質,你就能構建高併發網關、遊戲幀邏輯、複雜解析器、優雅的異步流程控制。記住:協程的藝術在於「在恰當的時機 yield,把控制權交還調度器」。

copyright © 萬盛學電腦網 all rights reserved