lua学习笔记(二)---lua中的coroutine

coroutine我自己的理解是伪中断。在调用coroutine.yeild时就会自动调用正在wait中的coroutine.resume。并且会把yeild里面的参数按顺序作为resume的第二、三等返回值返回。resume第一返回值是coroutine的状态。

function receive(prod)
    local status, value = coroutine.resume(prod)
    return value
end

function send(x)
    coroutine.yield(x)
end

function producer()
    local i = 0
    return coroutine.create(function()
        while true do
            local x = i
            i = i + 1
            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)
        print("received:" .. x)
    end
end

consumer(filter(producer()))

抄袭下一个现成的代码,这个代码打印如下。

   1 0

   2 1

 ...

原理就是先执行producer,filter 创建couroutine,consumer到receive(A)卡死在resume上,同时couroutine触发了filter里面的receive(B),couroutine触发了producer的send(0),yeild这时就执行到了最近的receive(B)中的resume并且把0传给了value。filter继续执行,将 1 0 传给send,这时send把值给receive(A),一个循环结束。

虽然这个看起来是多个函数之间的同步,但是实际上还是一个线程上的同步。主界面还是会卡死。so需要在线程中做这样的同步。

转载于:https://www.cnblogs.com/permanier/p/3168561.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值