lua学习笔记(六)

--创建协程,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()))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值