Lua学习笔记四——协同程序coroutine
lua中的协同程序类似于多线程,但是与多线程还是有点区别的,区别在于协同程序必须必须合作,且同一时刻只有运行一个协同程序。
function p()
print("Hello World")
end
这是一个简单的示例函数,下面看看协同程序的调用
co = coroutine.create(p)
print(co) --> thread: 003FBBF0
print(coroutine.status(co)) --> suspended
coroutine.resume(co) --> Hello World
print(coroutine.status(co)) --> dead
在上面的调用代码中,右边附上了打印输出,第一行是创建一个协同程序,第二行查看协同程序的返回值,第三行查看此时协同程序的状态,处于suspended(挂起)状态,第四行执行协同程序,第五行查看此时协同程序状态,处于dead(死亡)状态。
协同程序有四种状态,suspended(挂起)、running(运行)、dead(死亡)、normal(正常),
当调用coroutine.create后,处于挂起状态
调用coroutine.resume后,处于运行状态,执行完毕后,处于死亡状态
当一个协同程序a调用另一个协同程序b后,a就处于正常状态,b处于运行状态
协同程序传递参数:
co2 = coroutine.create(function(a, b)
coroutine.yield(a * b, a + b)
end)
print(coroutine.resume(co2, 2, 2009))
在resume调用中,除第一个值外,其余值都将传给yield,执行后的返回之中,第一个值为Boolean类型,协同程序运行是否正常,其余的值是对应yield的返回值。
转载自:http://blog.csdn.net/hong201/archive/2009/05/05/4151835.aspx
接触lua的协同程序
lua中没有真正的多线程,用了协同程序代替,照例来个demo看看,如下:
[cc lang="lua"]#!usr/bin/env lua
function receive(prod)
local status, value = coroutine.resume(prod)
return value
end
function send(v)
coroutine.yield(v)
end
-- product
function producer()
return coroutine.create(function()
while true do
local v =io.read()
send(v)
end
end)
end
--consumer
function consumer(prod)
while true do
local x = receive(prod)
io.write(x, "\n")
end
end
function filter(prod)
return coroutine.create(function()
for line = 1, math.huge do
local v = receive(prod)
v = string.format("%5d %s", line, v)
send(v)
end
end)
end
--main 协同程序
p = producer()
f = filter(p)
consumer(f)
[/cc]
就一个生产者--消费装模型,看看就行。
转载自:http://blog.csdn.net/hong201/archive/2009/04/06/4052754.aspx