--创建协程,coroutine表中名为create的函数创建协程,返回值为thread类型
co = coroutine.create(function () print("Hello") end)
print(co)
--查看协程状态 suspended running dead normal四种状态
print(coroutine.status(co))
--唤醒协程
coroutine.resume(co)
print(coroutine.status(co))
--coroutine.yield()挂起协程
co = coroutine.create(function() for i = 1,10 do print("co",i) coroutine.yield() end end)
coroutine.resume(co)
coroutine.resume(co)
coroutine.resume(co)
coroutine.resume(co)
coroutine.resume(co)
print(coroutine.status(co))
coroutine.resume(co)
coroutine.resume(co)
coroutine.resume(co)
coroutine.resume(co)
coroutine.resume(co)
--似乎最大次挂起不会使得协程直接进入死亡状态,需要再唤醒一次才会使得协程进入死亡状态
print(coroutine.status(co))
--试图唤醒死亡的协程 好像什么也没发生
coroutine.resume(co)
print(coroutine.status(co))
--协同程序coroutine.resume()会打印啥
--无yield时 协程主函数打印啥唤醒时就会打印啥
co = coroutine.create(function (a,b,c)
print("co",a,b,c)
end)
coroutine.resume(co,1,2,3)
--有yield时
co = coroutine.create(function(a,b)
coroutine.yield(a+b,a-b)
end
)
--打印唤醒函数会直接打印是否有错误和yield传入的参数
print(coroutine.resume(co,20,10))
--协程直接有返回值时
co = coroutine.create(function()
return 6,7
end
)
print(coroutine.resume(co))
--pipe管道filter过滤器
--接收产品
function receive(pro)
local status,value = coroutine.resume(pro)
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 consumer(pro)
while true do
local x = receive(pro)
print(x)
end
end
--过滤器
function filter(pro)
return coroutine.create(function()
for line = 1,math.huge do
local x = receive(pro)
x = string.format("%5d%s",line,x)
send(x)
end
end)
end
--生产并消费
consumer(filter(producer()))