1. 程式人生 > >Lua筆記——6.協同程序Coroutine

Lua筆記——6.協同程序Coroutine

rep mat lai 說明 -i 很多 until already ads

coroutine簡介:

協同程序與多線程情況下的線程比較類似:有自己的堆棧,自己的局部變量,有自己的指令指針(IP,instruction pointer),但可與其它協同程序共享全局變量等很多信息。
線程與協同程序的主要區別在於,一個具有多個協同程序的程序在任何時刻只能運行一個協同程序,並且正在運行的協同程序只會在其顯式地掛起時,它的執行才會暫停。

協同程序

Lua將所有協同函數存放於coroutine table中:

1.創建協同程序的方法

coroutine.create函數用於創建新的協同程序,其只有一個參數:一個函數,即協同程序將要運行的代碼。

--file: coroutine.lua

--創建一個協同程序,函數的代碼就是協同程序執行的內容,返回值為一個thread類型的數據
co = coroutine.create(function()
        print("Hello Lua!")
    end)

print(co)   -->thread: 02C3C518

2.協同程序的狀態

掛起態:suspended 當我們創建協同程序成功時,其為掛起態,即此時協同程序並未運行;使用函數yield可以使程序掛起

--可以用coroutine.status(co) 可以獲取剛剛創建co的狀態
print(coroutine.status(co))    -->suspended

運行態:running 函數coroutine.resume使協同程序由掛起狀態變為運行態;任務完成後便進入停止狀態

coroutine.resume(co)    -->Hello Lua!

終止態:dead 運行結束後

print(coroutine.status(co))     --> dead

--當協同程序處於終止態時,如果我們仍然希望resume它,將返回false和錯誤信息
--resume運行在保護模式下,因此,如果協同程序內部存在錯誤,Lua並不會拋出錯誤,而是將錯誤返回給resume函數
print(coroutine.resume(co)) -->false   cannot resume dead coroutine

代碼:

--file: coroutine.lua

co = coroutine.create(function()
        print("Hello Lua!")
    end)

print(co)   -->thread: 02C3C518

print(coroutine.status(co)) -->suspended

coroutine.resume(co)    -->Hello Lua!

print(coroutine.status(co)) -->dead

print(coroutine.resume(co)) -->false   cannot resume dead coroutine

3.協同程序之間通過resume-yield來交換數據

第一個例子中只有resume,沒有yield,resume把參數傳遞給協同的主程序

--file: para.lua

co = coroutine.create(function(data)
        print("The parameter is "..data..' .')
    end)

coroutine.resume(co,"para")    -->The parameter is para .

第二個例子,數據由yield傳給resume:返回 true表明調用成功,true之後的部分,即是yield的參數

co2 = coroutine.create(function(para1,para2)
        coroutine.yield(para1+1,para2+2)
    end)

print(coroutine.resume(co2,10,20))  -->true    11      22

數據也可以由resume傳給yield:

co3 = coroutine.create(function()
        print("test",coroutine.yield())
    end)

coroutine.resume(co3)
print("-----------------")
coroutine.resume(co3,"The parameter from resume to co3's yield func")    -->test    The parameter from resume to co3's yield func

第三個例子,協同代碼結束時的返回值,也會傳給resume,第一個返回值為true則表示成功調用,否則為false,之後為協同程序的返回值

co4 = coroutine.create(function(para1,para2)
        return para1 + para2
    end)

print(coroutine.resume(co4,10,20))  -->true    30

生產者-消費者問題

一個函數不斷地生產數據(比如從文件中讀取),另一個函數不斷的處理這些數據(比如寫到另一文件中)

--file: producer.lua

function receive(producer)  
    local status,value = coroutine.resume(producer)  
    return value  
end  
  
function send(x)  
    coroutine.yield(x)  
end  
  
function producer()  
    return coroutine.create(function()  
        for i = 1,100 do   
            send(i)  
        end  
    end)  
end  
  
function consumer(producer)  
    while true do  
        local value = receive(producer)  
        if value == 100 then 
        print("receive value: "..value.." done!!!")
        break 
    end  
        print("receive value: "..value)  
    end  
end

p = producer()

--開始時調用消費者,當消費者需要值時他喚起生產者生產值,生產者生產值後停止直到消費者再次請求
--這種設計稱為消費者驅動設計
consumer(p)    --> receive value: 1...100 done!!!

構造叠代器

我們可以將循環的叠代器看作生產者-消費者模式的特殊的例子。叠代函數產生值給循環體消費。所以可以使用協同來實現叠代器。協同的一個關鍵特征是它可以不斷顛倒調用者與被調用者之間的關系,這樣我們毫無顧慮的使用它實現一個叠代器,而不用保存叠代函數返回的狀態。

--TODO

非搶占式多線程

--TODO

使用Lua的Coroutine構建Event系統

EventLib

EventLib - An event library in pure lua (uses standard coroutine library)


    -- file: eventlib.lua
    
    local _M = { }
    _M._M = _M
    
    function _M:new(name)
        assert(self ~= nil and type(self) == "table" and self == _M, "Invalid EventLib table (make sure you're using ':' not '.')")
        local s = { }
        s.handlers = { }
        s.waiter = false
        s.args = nil
        s.waiters = 0
        s.EventName = name or "<Unknown Event>"
        s.executing = false
        return setmetatable(s, { __index = self })
    end
    _M.CreateEvent = _M.new
    
    function _M:Connect(handler)
        assert(self ~= nil and type(self) == "table", "Invalid Event (make sure you're using ':' not '.')")
        assert(type(handler) == "function", "Invalid handler. Expected function got " .. type(handler))
        assert(self.handlers, "Invalid Event")
        table.insert(self.handlers, handler)
        local t = { }
        t.Disconnect = function()
            return self:Disconnect(handler)
        end
        t.disconnect = t.Disconnect
        return t
    end
    _M.connect = _M.Connect
    
    function _M:Disconnect(handler)
        assert(self ~= nil and type(self) == "table", "Invalid Event (make sure you're using ':' not '.')")
        assert(type(handler) == "function" or type(handler) == "nil", "Invalid handler. Expected function or nil, got " .. type(handler))
        --If Direct Call DisConnect() , It Well be Direct clear the handlers
        if not handler then
            self.handlers = { }
        else
            for k, v in pairs(self.handlers) do
                if v == handler then
                    self.handlers[k] = nil
                    return k
                end
            end
        end
    end
    _M.disconnect = _M.Disconnect
    
    function _M:DisconnectAll()
        assert(self ~= nil and type(self) == "table", "Invalid Event (make sure you're using ':' not '.')")
        self:Disconnect()
    end
    
    local function spawn(f)
        return coroutine.resume(coroutine.create(function()
            f()
        end))
    end
    
    _M.Spawn = spawn
    _M.spawn = spawn
    
    function _M:Fire(...)
        assert(self ~= nil and type(self) == "table", "Invalid Event (make sure you're using ':' not '.')")
        self.args = { ... }
        self.executing = true
        --[[
        if self.waiter then
            self.waiter = false
            for k, v in pairs(self.waiters) do
                coroutine.resume(v)
            end
        end]]--
        self.waiter = false
        local i = 0
        assert(self.handlers, "no handler table")
    
        for k, v in pairs(self.handlers) do
            i = i + 1
            spawn(function() 
                v(unpack(self.args)) 
                i = i - 1
                if i == 0 then self.executing = false end
            end)
        end
        
        self:WaitForWaiters()
        self.args = nil
        --self.executing = false
    end
    _M.Simulate = _M.Fire
    _M.fire = _M.Fire
    
    function _M:Wait()
        assert(self ~= nil and type(self) == "table", "Invalid Event (make sure you're using ':' not '.')")
        self.waiter = true
        self.waiters = self.waiters + 1
        --[[
        local c = coroutine.create(function()
            coroutine.yield()
            return unpack(self.args)
        end)
        
        table.insert(self.waiters, c)
        coroutine.resume(c)
        ]]
        
        while self.waiter or not self.args do if wait then wait() end end
        self.waiters = self.waiters - 1
        return unpack(self.args)
    end
    _M.wait = _M.Wait
    
    function _M:ConnectionCount()
        assert(self ~= nil and type(self) == "table", "Invalid Event (make sure you're using ':' not '.')")
        return #self.handlers
    end
    
    function _M:Destroy()
        assert(self ~= nil and type(self) == "table", "Invalid Event (make sure you're using ':' not '.')")
        self:DisconnectAll()
        for k, v in pairs(self) do
            self[k] = nil
        end
        setmetatable(self, { })
    end
    _M.destroy = _M.Destroy
    _M.Remove = _M.Destroy
    _M.remove = _M.Destroy
    
    function _M:WaitForCompletion()
        assert(self ~= nil and type(self) == "table", "Invalid Event (make sure you're using ':' not '.')")
        while self.executing do if wait then wait() end end
        while self.waiters > 0 do if wait then wait() end end
    end
    
    function _M:IsWaiting()
        assert(self ~= nil and type(self) == "table", "Invalid Event (make sure you're using ':' not '.')")
        return self.waiter or self.waiters > 0
    end
    
    function _M:WaitForWaiters()
        assert(self ~= nil and type(self) == "table", "Invalid Event (make sure you're using ':' not '.')")
        while self.waiters > 0 do if wait then wait() end end
    end
    
    if shared and Instance then -- ROBLOX support
        shared.EventLib = _M 
        _G.EventLib = _M
    end
    
    return _M

Event

    
    --file:events.lua
    local EventLib = require "eventlib"
    
    local Event = {}
    
    local events = {}
    
    function Event.AddListener(eventName,handler)
        assert(type(eventName) == "string" , "event parameter in addlistener function has to be string, " .. type(eventName) .. " not right.")
        assert(type(handler) == "function", "handler parameter in addlistener function has to be function, " .. type(handler) .. " not right")
    
        if not events[eventName] then
            events[eventName] = EventLib:CreateEvent(eventName)     
        end
    
        --conn this handler
        events[eventName]:connect(handler)
    end
    
    function Event.Brocast(eventName,...)
        if not events[eventName] then
            error("brocast " .. eventName .. " has no event.")
        else
            events[eventName]:fire(...)
        end
    end
    
    function Event.RemoveListener(eventName,handler)
        if not events[eventName] then
            error("remove " .. eventName .. " has no event.")
        else
            events[eventName]:disconnect(handler)
        end
    end
    
    return Event


Usage Code

測試events.lua


    --file: testEvent.lua
    local Event = require "events"
    
    local func1 = function(...) print(unpack{...}) end
    local func2 = function(...) print(unpack{...}) end
    
    Event.AddListener("Test Event" , func1);
    
    Event.AddListener("Test Event" ,func2);
    
    Event.AddListener("Test Event" , function() print("Event test check!") end);
    
    Event.Brocast("Test Event","args1",2,{3,4,5});
    
    
    print("------------remove func2 -------------")
    
    Event.RemoveListener("Test Event" ,func2)
    
    Event.Brocast("Test Event","args1",2,{3,4,5});

eventlib.lua

eventlib.lua的說明

    
    -- Description:
    -- ROBLOX has an event library in its RbxUtility library, but it isn't pure Lua. 
    -- It originally used a BoolValue but now uses BindableEvent. I wanted to write
    -- it in pure Lua, so here it is. It also contains some new features.
    -- 
    -- 
    -- API:
    -- 
    -- EventLib
    --   new([name])
    --     aliases: CreateEvent
    --     returns: the event, with a metatable __index for the EventLib table
    --   Connect(event, func)
    --     aliases: connect
    --     returns: a Connection
    --   Disconnect(event, [func])
    --     aliases: disconnect
    --     returns: the index of [func]
    --     notes: if [func] is nil, it removes all connections
    --   DisconnectAll(event)
    --     notes: calls Disconnect()
    --   Fire(event, ... <args>)
    --     aliases: Simulate, fire
    --     notes: resumes all :wait() first
    --   Wait(event)
    --     aliases: wait
    --     returns: the Fire() arguments
    --     notes: blocks the thread until Fire() is called
    --   ConnectionCount(event)
    --     returns: the number of current connections
    --   Spawn(func)
    --     aliases: spawn
    --     returns: the result of func
    --     notes: runs func in a separate coroutine/thread
    --   Destroy(event)
    --     aliases: destroy, Remove, remove
    --     notes: renders the event completely useless
    --   WaitForCompletion(event)
    --     notes: blocks current thread until the current event Fire() is done
    --       If a connected function calls WaitForCompletion, it will hang forever
    --   IsWaiting(event)
    --     returns: if the event has any waiters
    --   WaitForWaiters(event)
    --     notes: waits for all waiters to finish. Called in Fire() to make sure that all
    --       the waiting threads are done before settings self.args to nil
    --   
    -- Event
    --   [All EventLib functions]
    --   EventName
    --     Property, defaults to "<Unknown Event>"
    --   <Private fields>
    --     handlers, waiter, args, waiters, executing, 
    -- 
    -- Connection
    --   Disconnect
    --     aliases: disconnect
    --     returns: the result of [Event].Disconnect
    -- 
    -- Basic usage (there are some tests on the bottom):
    --  local EventLib = require'EventLib' 
    -- For ROBLOX use: repeat wait() until _G.EventLib local EventLib = _G.EventLib
    --  
    --  local event = EventLib:new()
    --  local con = event:Connect(function(...) print(...) end)
    --  event:Fire("test") --> 'test' is print'ed
    --  con:disconnect()
    --  event:Fire("test") --> nothing happens: no connections
    -- 
    -- Supported versions/implementations of Lua:
    -- Lua 5.1, 5.2
    -- SharpLua 2
    -- MetaLua
    -- RbxLua (automatically registers if it detects ROBLOX)
    
    --[[
    Issues:
    - None, but see [Todo 1]
    
    Todo:
    - fix Wait() for non-roblox clients without a wait function...
    
    Changelog:
    
    v1.0
    - Initial version

eventlib.lua測試代碼


    --file:testEventLib.lua
    local EventLib = require "eventlib"
    
    if true then
        local TestEvent = EventLib:new("test")
        print("EventName : " .. TestEvent.EventName)
        
        local f = function(...) 
            print("| Fired!", ...)
        end
        
        local e2 = TestEvent:connect(f)
        
        TestEvent:fire("arg1", 5, { })
        -- Would work in a ROBLOX Script, but not on Lua 5.1...
        if script ~= nil and failhorribly then
            spawn(function() print("Wait() results", TestEvent:wait()) print"|- done waiting!" end)
        end
        
        TestEvent:fire(nil, "x")
        
        print("Disconnected TestEvents index:", TestEvent:disconnect(f))
        
        print("Couldn't disconnect an already disconnected handler?", e2:disconnect()==nil)
        
        print("Connections:", TestEvent:ConnectionCount())
        
        assert(TestEvent:ConnectionCount() == 0 and TestEvent:ConnectionCount() == #TestEvent.handlers)
        
        TestEvent:connect(f)
        TestEvent:connect(function() print"Throwing error... " error("...") end)
        TestEvent:fire("Testing throwing an error...")
        TestEvent:disconnect()
        TestEvent:Simulate()
        
        f("plain function call")
        
        assert(TestEvent:ConnectionCount() == 0)
        
        if wait then
            TestEvent:connect(function() wait(2, true) print'fired after waiting' end)
            TestEvent:Fire()
            TestEvent:WaitForCompletion()
            print'Done!'
        end
        
        local failhorribly = false
        if failhorribly then -- causes an eternal loop in the WaitForCompletion call
            TestEvent:connect(function() TestEvent:WaitForCompletion() print'done with connected function' end)
            TestEvent:Fire()
            print'done'
        end
        
        TestEvent:Destroy()
        assert(not TestEvent.EventName and not TestEvent.Fire and not TestEvent.Connect)
    end

REF

http://book.luaer.cn/

Lua筆記——6.協同程序Coroutine