• lu协程练习


    生产者和消费者问题:
    当协程调用yield时,从一个悬而未决的resume中返回。
    简单的协程练习:

    function receive()
        local status,value = coroutine.resume(producer)
        return status,value
    end
    
    function send(x)
        coroutine.yield(x)
    end
    
    producer = coroutine.create(
    function()
        local x = 0
        while true do
            x = x+1
            if(x > 10) then
                break
            end
            send(x)
        end
    end)
    
    
    local status,res
    repeat
     status,res = receive()
    print(status, res)
    until(nil == res)

    输出:

    >lua -e "io.stdout:setvbuf 'no'" "1.lua"
    true 1
    true 2
    true 3
    true 4
    true 5
    true 6
    true 7
    true 8
    true 9
    true 10
    true nil
    >Exit code: 0

    这种模式被称为消费者驱动模式。

    过滤器filter是一种位于生产者和消费者之间的处理函数,用于对数据进行变换。它既是一个生产者又是消费者,他唤醒生产者产生new value,然后又将变换后的值传给消费者。

     表示自己写的代码,出问题了:

    function receive(prod)
        local value = coroutine.resume(prod)
        return value
    end
    
    function send(x)
        coroutine.yield(x)
    end
    
    x = 0
    function producer()
    return coroutine.create(
    function()
        x = x + 1
        print(sting.format("producer:%d.
    ",x))
        return x
    end)
    end
    
    function filter(prod)
        return coroutine.create(
        function()
        local x = receive(prod)
        x = string.format("Add:%d",x)
        send(x)
        end
    )
    end
    
    function consumer(prod)
    repeat
        res = receive(prod)
        print(res)
    until (nil == res)
    end
    
    
    p = producer()
    f = filter(p)
    print(x)
    consumer(f)

    晚上回去看看怎么回事。

  • 相关阅读:
    Spring MVC 拦截器
    spring中MultiActionController的数据绑定
    Hibernate多对多配置
    hibernate实体类配置文件问题(字段使用默认值)
    HibernateTemplate类的使用 (转)
    javascript小笔记(一)
    spring整合hibernate(2)
    Sina AppEngine 的bug
    找工作
    天下武功唯快不破
  • 原文地址:https://www.cnblogs.com/xiangshancuizhu/p/3334339.html
Copyright © 2020-2023  润新知