Lua协程的一个例子

很久没记录笔记了,还是养成不了记录的习惯

下面是来自 programming in lua的一个协程的例(生产者与用户的例子)

帖代码,慢慢理解


-- Programming in Lua Coroutine(协程)
--[[
coroutine.create
coroutine.resume
coroutine.running
coroutine.status
coroutine.wrap
coroutine.yield
--]]

--管道和过滤

--生产者与用户的例子

--[[
************************************************
函数 :send
用途 :暂停线程
参数 :发送给下一次恢复的线程的数据
返回值:无
************************************************
--]]
function send(x)
coroutine.yield(x)
end

--[[
************************************************
函数 :receive
用途 :从线程中检索数据
参数 :(function)需要被检索的线程
返回值:(object)从上次暂停的线程中获取的数据
************************************************
--]]
function receive(co)
local status, value = coroutine.resume(co)
return value
end

--[[
************************************************
函数:producer
功能:不断生产值的函数(即生产者)
参数:无
返回值:线程
************************************************
--]]
function producer()
return coroutine.create(
function()
while true do
local x = io.read()
--print(x)
send(x)
end
end)
end

--[[
************************************************
函数:fitler
功能:改造由producer产生的值(即加工器)
参数:线程(生产者)
返回值:线程(经过加工的线程)
************************************************
--]]
function fitler(co)
return coroutine.create(function()
--math.huge是个无穷大的数
for line=1, math.huge do
local x = receive(co)
--被加工后的数据
x = string.format("%5d %s",line, x)
send(x)
end
end)
end


--[[
************************************************
函数:consumer
功能:不断检索值的函数(用户)
参数:线程(生产者)
返回值:无
************************************************
--]]
function consumer(co)
while true do
local x = receive(co)
--print(x)
io.write(x, "\n")
end
end

--流程:生产》加工》用户使用
--生产
p = producer()
--加工
f = fitler(p)
--用户使用
consumer(f)

 

 

posted @ 2014-03-18 11:15  A.Kun  阅读(374)  评论(0编辑  收藏  举报