zoukankan      html  css  js  c++  java
  • lua-coroutine

    两个协程,通过resume/yield函数参数(或者return语句)向对方传送数据,通过resume/yield函数返回值来从对方处获取传送数据
     
            function coroutine_func(resume1.Args)
                        yield1  return resume2.Args
                        yield2  return resume3.Args
              end
                                 
               resume1() return true,yield1.Args
                    resume2() return true,yield2.Args
                    resume3() return true,coroutine_func.return
            
                    将Resume作为一个服务A, coroutine_func作为一个服务B
                    则  A传递数据(resume1.Args)给B, B获取后(由函数的参数获取),把响应数据(yield1.Args)>
                    A继续传递数据给(resume2.Args)给B,B获取后(由yield1.return获取),把响应数据(yield2.A
                    即,A(resume)和B(yield)都是通过参数来向对方传送数据,而通过返回值来从对方处获取传送
     
        一个异步的实现方法为 
                        function runAsyncFunc(func,...)
                            local current = coroutine.running 
                            func.callback = function() coroutine.resume(current) end
                            coroutine.yield --等待动作完成后通过回调函数来恢复执行
                        end  
     
      一个读写消费者的例子:
      
      function  producer()
        return coroutine.create(function()
            while true do 
              local data = io.read()
              coroutine.yield(data)
            end
          end)
      end 
     
      function consumer(p)
        while true do
          local status, data = coroutine.resume(p)
          print(data)
        end 
      end

      consumer(producer())

      添加 filter:

          function filter(source)

        return coroutine.create(function ()

            for x = 1, 10 do

              local status, data = coroutine.resume(source)

              cortine.yield('from filter' .. data)

            end

          end)

      end 

      function consumer(filter)

        while true do

          local status, data = coroutine.resume(filter)

          if not status then return end

          print (data) 

        end

         end

      comsumer(filter(producer()))

      

  • 相关阅读:
    QR code 乱谈(一)
    用JAVA实现数字水印(可见)
    ctf总结
    Unix/Linux常用命令
    C语言概述
    C语言发发展历史
    为什么要学习C语言
    计算机应用领域
    计算机发展趋势
    如何学习计算机
  • 原文地址:https://www.cnblogs.com/reach/p/4046150.html
Copyright © 2011-2022 走看看