lua中让消费者作为协程,生产者作为主线程

问题描述 投票:0回答:1

这是消费者-生产者,生产者作为协程,消费者作为主线程:

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

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

 function producer ()
   return coroutine.create(function ()
       while true do
        local x = io.read()
        -- produce new value
        send(x)
       end
    end)
  end

  function filter (prod)
     return coroutine.create(function ()
        for line = 1, math.huge do
            local x = receive(prod)
            -- get new value
            x = string.format("%5d %s", line, x)
            send(x)
            -- send it to consumer
         end
      end)
   end

   function consumer (prod)
      while true do
        local x = receive(prod)
        io.write(x, "\n")
      end
   end

   -- get new value
   -- consume new value
   consumer(filter(producer()))

这是我的答案 bt 没有按预期运行:

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

   function send (cons, x)
     local status, value = coroutine.resume(cons, x)
     return value
   end

  function producer (cons)
   while true do
    local x = io.read()
    -- produce new value
    send(cons, x)
   end
 end

 function filter (cons)
   return coroutine.create(function (x)
     for line = 1, math.huge do
        local _, x = receive(x)
        -- get new value
        x = string.format("%5d %s", line, x)
        send(cons, x)
        -- send it to consumer
    end
    end)
  end

  function consumer ()
   return coroutine.create(function(x) 
      while true do
        local x = receive(x)
        io.write(x, "\n")
      end
    end)
 end

 -- get new value
 -- consume new value
   producer(filter(consumer()))

事情是当进入本地 x = receive(x) 进入 filter() 函数时,然后它会再次进入 Producer() 等待新输入而不格式化 x 输入。 有什么建议吗?我不想改变最初的实现方式,这意味着recieve()绑定到consumer()中,send()绑定到reciever()中。

lua consumer producer
1个回答
0
投票

接收者没有返回任何内容,让我们添加一个返回。

function receive(x)
    return coroutine.yield(x)
end

在您的示例中接收器仅返回一个值,让我们删除

_

local x = receive(x)

然后你所有的消费者,过滤器等都是一个输入延迟,因为你忽略了第一个x,然后进入循环。

© www.soinside.com 2019 - 2024. All rights reserved.