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


推荐阅读
  • 本文介绍了lua语言中闭包的特性及其在模式匹配、日期处理、编译和模块化等方面的应用。lua中的闭包是严格遵循词法定界的第一类值,函数可以作为变量自由传递,也可以作为参数传递给其他函数。这些特性使得lua语言具有极大的灵活性,为程序开发带来了便利。 ... [详细]
  • 基于layUI的图片上传前预览功能的2种实现方式
    本文介绍了基于layUI的图片上传前预览功能的两种实现方式:一种是使用blob+FileReader,另一种是使用layUI自带的参数。通过选择文件后点击文件名,在页面中间弹窗内预览图片。其中,layUI自带的参数实现了图片预览功能。该功能依赖于layUI的上传模块,并使用了blob和FileReader来读取本地文件并获取图像的base64编码。点击文件名时会执行See()函数。摘要长度为169字。 ... [详细]
  • HDU 2372 El Dorado(DP)的最长上升子序列长度求解方法
    本文介绍了解决HDU 2372 El Dorado问题的一种动态规划方法,通过循环k的方式求解最长上升子序列的长度。具体实现过程包括初始化dp数组、读取数列、计算最长上升子序列长度等步骤。 ... [详细]
  • 本文讨论了如何优化解决hdu 1003 java题目的动态规划方法,通过分析加法规则和最大和的性质,提出了一种优化的思路。具体方法是,当从1加到n为负时,即sum(1,n)sum(n,s),可以继续加法计算。同时,还考虑了两种特殊情况:都是负数的情况和有0的情况。最后,通过使用Scanner类来获取输入数据。 ... [详细]
  • Mac OS 升级到11.2.2 Eclipse打不开了,报错Failed to create the Java Virtual Machine
    本文介绍了在Mac OS升级到11.2.2版本后,使用Eclipse打开时出现报错Failed to create the Java Virtual Machine的问题,并提供了解决方法。 ... [详细]
  • 在说Hibernate映射前,我们先来了解下对象关系映射ORM。ORM的实现思想就是将关系数据库中表的数据映射成对象,以对象的形式展现。这样开发人员就可以把对数据库的操作转化为对 ... [详细]
  • 本文介绍了在SpringBoot中集成thymeleaf前端模版的配置步骤,包括在application.properties配置文件中添加thymeleaf的配置信息,引入thymeleaf的jar包,以及创建PageController并添加index方法。 ... [详细]
  • 本文介绍了使用Java实现大数乘法的分治算法,包括输入数据的处理、普通大数乘法的结果和Karatsuba大数乘法的结果。通过改变long类型可以适应不同范围的大数乘法计算。 ... [详细]
  • 本文讨论了Alink回归预测的不完善问题,指出目前主要针对Python做案例,对其他语言支持不足。同时介绍了pom.xml文件的基本结构和使用方法,以及Maven的相关知识。最后,对Alink回归预测的未来发展提出了期待。 ... [详细]
  • Windows下配置PHP5.6的方法及注意事项
    本文介绍了在Windows系统下配置PHP5.6的步骤及注意事项,包括下载PHP5.6、解压并配置IIS、添加模块映射、测试等。同时提供了一些常见问题的解决方法,如下载缺失的msvcr110.dll文件等。通过本文的指导,读者可以轻松地在Windows系统下配置PHP5.6,并解决一些常见的配置问题。 ... [详细]
  • 本文介绍了C#中数据集DataSet对象的使用及相关方法详解,包括DataSet对象的概述、与数据关系对象的互联、Rows集合和Columns集合的组成,以及DataSet对象常用的方法之一——Merge方法的使用。通过本文的阅读,读者可以了解到DataSet对象在C#中的重要性和使用方法。 ... [详细]
  • 本文介绍了OC学习笔记中的@property和@synthesize,包括属性的定义和合成的使用方法。通过示例代码详细讲解了@property和@synthesize的作用和用法。 ... [详细]
  • 知识图谱——机器大脑中的知识库
    本文介绍了知识图谱在机器大脑中的应用,以及搜索引擎在知识图谱方面的发展。以谷歌知识图谱为例,说明了知识图谱的智能化特点。通过搜索引擎用户可以获取更加智能化的答案,如搜索关键词"Marie Curie",会得到居里夫人的详细信息以及与之相关的历史人物。知识图谱的出现引起了搜索引擎行业的变革,不仅美国的微软必应,中国的百度、搜狗等搜索引擎公司也纷纷推出了自己的知识图谱。 ... [详细]
  • 本文讲述了作者通过点火测试男友的性格和承受能力,以考验婚姻问题。作者故意不安慰男友并再次点火,观察他的反应。这个行为是善意的玩人,旨在了解男友的性格和避免婚姻问题。 ... [详细]
  • 本文介绍了操作系统的定义和功能,包括操作系统的本质、用户界面以及系统调用的分类。同时还介绍了进程和线程的区别,包括进程和线程的定义和作用。 ... [详细]
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社区 版权所有