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
--Compat the new 5.3ver lua
local unpack = unpack or table.unpack
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"
--Compat the new 5.3ver lua
local unpack = unpack or table.unpack
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
testEventLib.lua输出结果:
REF