热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Lua笔记——6.协同程序Coroutine

coroutine简介:协同程序与多线程情况下的线程比较类似:有自己的堆栈,自己的局部变量,有自己的指令指针(IP,instructionpointer),但可与其它协同程序共享全

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 ""
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, ... )
-- 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 ""
--
-- 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/


推荐阅读
  • 在1995年,Simon Plouffe 发现了一种特殊的求和方法来表示某些常数。两年后,Bailey 和 Borwein 在他们的论文中发表了这一发现,这种方法被命名为 Bailey-Borwein-Plouffe (BBP) 公式。该问题要求计算圆周率 π 的第 n 个十六进制数字。 ... [详细]
  • 二维码的实现与应用
    本文介绍了二维码的基本概念、分类及其优缺点,并详细描述了如何使用Java编程语言结合第三方库(如ZXing和qrcode.jar)来实现二维码的生成与解析。 ... [详细]
  • publicclassBindActionextendsActionSupport{privateStringproString;privateStringcitString; ... [详细]
  • 本文介绍了如何通过C#语言调用动态链接库(DLL)中的函数来实现IC卡的基本操作,包括初始化设备、设置密码模式、获取设备状态等,并详细展示了将TextBox中的数据写入IC卡的具体实现方法。 ... [详细]
  • 本文将从基础概念入手,详细探讨SpringMVC框架中DispatcherServlet如何通过HandlerMapping进行请求分发,以及其背后的源码实现细节。 ... [详细]
  • 本文探讨了如何通过优化 DOM 操作来提升 JavaScript 的性能,包括使用 `createElement` 函数、动画元素、理解重绘事件及处理鼠标滚动事件等关键主题。 ... [详细]
  • 本文介绍了SIP(Session Initiation Protocol,会话发起协议)的基本概念、功能、消息格式及其实现机制。SIP是一种在IP网络上用于建立、管理和终止多媒体通信会话的应用层协议。 ... [详细]
  • 本文详细介绍了JQuery Mobile框架中特有的事件和方法,帮助开发者更好地理解和应用这些特性,提升移动Web开发的效率。 ... [详细]
  • 本文详细介绍了C++中的构造函数,包括其定义、特点以及如何通过构造函数进行对象的初始化。此外,还探讨了转换构造函数的概念及其在不同情境下的应用,以及如何避免不必要的隐式类型转换。 ... [详细]
  • 数据类型--char一、char1.1char占用2个字节char取值范围:【0~65535】char采用unicode编码方式char类型的字面量用单引号括起来char可以存储一 ... [详细]
  • 本文详细介绍了iOS应用的生命周期,包括各个状态及其转换过程中的关键方法调用。 ... [详细]
  • Windows操作系统提供了Encrypting File System (EFS)作为内置的数据加密工具,特别适用于对NTFS分区上的文件和文件夹进行加密处理。本文将详细介绍如何使用EFS加密文件夹,以及加密过程中的注意事项。 ... [详细]
  • 如何在PHP中安装Xdebug扩展
    本文介绍了如何从PECL下载并编译安装Xdebug扩展,以及如何配置PHP和PHPStorm以启用调试功能。 ... [详细]
  • 在使用 Nginx 作为服务器时,发现 Chrome 能正确从缓存中读取 CSS 和 JS 文件,而 Firefox 却无法有效利用缓存,导致加载速度显著变慢。 ... [详细]
  • 本文探讨了程序员这一职业的本质,认为他们是专注于问题解决的专业人士。文章深入分析了他们的日常工作状态、个人品质以及面对挑战时的态度,强调了编程不仅是一项技术活动,更是个人成长和精神修炼的过程。 ... [详细]
author-avatar
yeeling610
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有