热门标签 | 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/


推荐阅读
  • 解决SQL Server数据库sa登录名无法连接的问题
    在安装SQL Server数据库后,使用Windows身份验证成功,但使用SQL Server身份验证时遇到问题。本文将介绍如何通过设置sa登录名的密码、启用登录名状态以及开启TCP协议来解决这一问题。 ... [详细]
  • Framework7:构建跨平台移动应用的高效框架
    Framework7 是一个开源免费的框架,适用于开发混合移动应用(原生与HTML混合)或iOS&Android风格的Web应用。此外,它还可以作为原型开发工具,帮助开发者快速创建应用原型。 ... [详细]
  • 解决Bootstrap DataTable Ajax请求重复问题
    在最近的一个项目中,我们使用了JQuery DataTable进行数据展示,虽然使用起来非常方便,但在测试过程中发现了一个问题:当查询条件改变时,有时查询结果的数据不正确。通过FireBug调试发现,点击搜索按钮时,会发送两次Ajax请求,一次是原条件的请求,一次是新条件的请求。 ... [详细]
  • 本文详细介绍了Linux系统中用于管理IPC(Inter-Process Communication)资源的两个重要命令:ipcs和ipcrm。通过这些命令,用户可以查看和删除系统中的消息队列、共享内存和信号量。 ... [详细]
  • LDAP服务器配置与管理
    本文介绍如何通过安装和配置SSSD服务来统一管理用户账户信息,并实现其他系统的登录调用。通过图形化交互界面配置LDAP服务器,确保用户账户信息的集中管理和安全访问。 ... [详细]
  • 如果应用程序经常播放密集、急促而又短暂的音效(如游戏音效)那么使用MediaPlayer显得有些不太适合了。因为MediaPlayer存在如下缺点:1)延时时间较长,且资源占用率高 ... [详细]
  • 自动验证时页面显示问题的解决方法
    在使用自动验证功能时,页面未能正确显示错误信息。通过使用 `dump($info->getError())` 可以帮助诊断和解决问题。 ... [详细]
  • 本文介绍了如何使用 CMD 批处理脚本进行文件操作,包括将指定目录下的 PHP 文件重命名为 HTML 文件,并将这些文件复制到另一个目录。 ... [详细]
  • NX二次开发:UFUN点收集器UF_UI_select_point_collection详解
    本文介绍了如何在NX中使用UFUN库进行点收集器的二次开发,包括必要的头文件包含、初始化和选择点集合的具体实现。 ... [详细]
  • 本文详细介绍了如何解决DNS服务器配置转发无法解析的问题,包括编辑主配置文件和重启域名服务的具体步骤。 ... [详细]
  • 数字资产量化交易通过大数据分析,以客观的方式制定交易决策,有效减少人为的主观判断和情绪影响。本文介绍了几种常见的数字资产量化交易策略,包括搬砖套利和趋势交易,并探讨了量化交易软件的开发前景。 ... [详细]
  • 自定义滚动条美化页面内容
    当页面内容超出显示范围时,为了提升用户体验和页面美观,通常会添加滚动条。如果默认的浏览器滚动条无法满足设计需求,我们可以自定义一个符合要求的滚动条。本文将详细介绍自定义滚动条的实现过程。 ... [详细]
  • importpymysql#一、直接连接mysql数据库'''coonpymysql.connect(host'192.168.*.*',u ... [详细]
  • 微软推出Windows Terminal Preview v0.10
    微软近期发布了Windows Terminal Preview v0.10,用户可以在微软商店或GitHub上获取这一更新。该版本在2月份发布的v0.9基础上,新增了鼠标输入和复制Pane等功能。 ... [详细]
  • 两个条件,组合控制#if($query_string~*modviewthread&t(&extra(.*)))?$)#{#set$itid$1;#rewrite^ ... [详细]
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社区 版权所有