Lua过滤器协同

来源:互联网 发布:mysql e 执行sql 编辑:程序博客网 时间:2024/04/28 03:40
这篇文章主要介绍了Lua中的协同程序探究,本文讲解了什么是协同程序、创建协同程序、更像样的协同程序、让协同程序挂起、resume操作的返回值,需要的朋友可以参考下。

什么是协同程序(coroutinue)

大家都知道线程吧?都知道多线程吧?协同程序就和这线程差不多,但是又有比较明显的区别。

多个协同程序在任意时刻只能执行一个,虽然线程在某种意义上也是这样,但这不是一样的概念。

换句话说,一个协同程序在运行的时候,其他协同程序是无法获得执行的机会的。
只有正在运行的协同程序主动挂起时,其他协同程序才有机会执行。
 
而线程呢?即使不主动休眠,也很有可能因为轮片时间到达而把执行机会让给其他线程。


Lua过滤器协同

function receive(prod)
 local status,value = coroutine.resume(prod)
 return value
end
function send(x)
 coroutine.yield(x)
end
function producer()
 return coroutine.create(function()
  while true do
  local x = io.read()  --创建新的值
  send(x)
  end
 end)
end
function filter(prod)
 return coroutine.create(function()
  local line = 1
  while true do
   local x = receive(prod) --得到新的值
   x = string.format("%5d %s,line,x")
   send(x)               --送到consumer
   line = line + 1
  end
 end)
end
function consumer(prod)
 while true do
  local x = receive(prod)  --得到新的值
  io.write(x,"\n")  --consumer新的值
 end
end
consumer(filter(producer()))  --调用

--[[
另外调用方式

p = producer()
f = filter(p)
consumer(f)
--]]

0 0
原创粉丝点击