一协程的状态
分为四种:
挂起(suspended):当创建一个协程时它便处于挂起状态,所以当我们创建协程时他不会自动执行,调用coroutine.yield时也是变成挂起状态
运行(running):调用coroutine.resume时便处于运行状态
死亡(dead):当协程运行结束之后便处于dead状态,而且无法返回
正常(normal):当一个协程a唤起另一个协程b,a变处于正常状态
co = coroutine.create(function()
for i= 1,3 do
coroutine.yield(i)
end
end)
print(coroutine.resume(co))--true 1
print(coroutine.status(co))--suspended
print(coroutine.resume(co))--true 2
print(coroutine.status(co))--suspended
print(coroutine.resume(co))--true 3
print(coroutine.status(co))--suspended
print(coroutine.resume(co))--true
print(coroutine.status(co))--dead
print(coroutine.resume(co))--false
实现生产者消费者问题
生产者:不断产生新值
消费者:不断消费这些值
--唤醒生产者执行产生一个新值
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()
while true do
local x = io.read()--产生新值
send(x)
end
end)
end
function filter(prod)
return coroutine.create(function()
for line = 1,math.huge do
local x= receive(prod)--接收新值
x = string.format("%5d %s",line ,x)
send(x)--将新值发送给消费者
end
end)
end
--消费者
function consumer(prod)
while true do
local x = receive(prod)--接收新值
io.write(x,"\n")
end
end
p = producer()
f = filter(p)
consumer(f)