为什么我的用lua协程实现的生产者消费者模型不能按预期工作?
2020-10-6 11:36:23
收藏:0
阅读:137
评论:2
我使用协程实现了一个生产者消费者模型。我的代码如下:
function send(prod, x)
coroutine.resume(prod, x)
end
function receive()
local x = coroutine.yield()
return x
end
function consumer()
return coroutine.create(function ()
while true do
local x = receive()
io.write(x, "\n")
end
end)
end
function producer(prod)
while true do
local x = io.read()
send(prod, x)
end
end
producer(consumer())
第一个输入消息("Hello World")消失了。它应该被打印两次,但现在只有一次。我认为,我生产者消费者模式的流程图应该像这样:
我理解错了吗?
点赞
用户4984564
第一次执行“resume”协同程序时,它不会直接跳转到第一个“yield”,而是使用给定的参数调用包装函数:
local co = coroutine.wrap(function(aaa)
print(aaa) -- 打印 "first"
print(coroutine.yield()) -- 打印 "second"
end)
co("first")
co("second")
在你的代码中,有一个简单的方法可以解决这个问题:
local send, receive =
coroutine.resume, coroutine.yield
function consumer()
return coroutine.create(function(x)
while true do
io.write(x, "\n")
x = receive()
end
end)
end
function producer(consumer)
while true do
local x = io.read()
send(consumer, x)
end
end
producer(consumer())
2020-10-07 07:58:25
评论区的留言会收到邮件通知哦~
推荐文章
- Lua 虚拟机加密load(string.dump(function)) 后执行失败问题如何解决
- 我想创建一个 Nginx 规则,禁止访问
- 如何将两个不同的lua文件合成一个 东西有点长 大佬请耐心看完 我是小白研究几天了都没搞定
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?



在输入第一个字符串后,函数按以下顺序调用:
sendconsumer返回的协程receiveproducer然后程序等待用户输入。local x = coroutine.yield(),因此local x = receive()会回到producer,此时还没有执行io.write(x, "\n")。用户输入第二行后,会按以下方式执行:
sendlocal x = receive()后 ,consumer被恢复并打印第二个输入。consumer调用receivereceive会回到producer以下是更正确的代码:
local function send(x) coroutine.yield(x) end local function receive(prod) local status, value = coroutine.resume(prod) return value end local function producer() return coroutine.create( function() while true do local x = io.read() -- 产生新值 send(x) end end ) end function consumer(prod) while true do local x = receive(prod) -- 获取新值 io.write(x, "\n") -- 消耗新值 end end consumer(producer())注意,它是
consumer(producer()),而不是另一个方式。还要注意producer是协程,而不是consumer。send会挂起,而receive会恢复。consumer开始程序,一遍又一遍地恢复producer。如果像你的例子那样,反过来,直到第二次迭代,consumer才准备好消费产品。更新: 以下是“强制饲养”,即生产者驱动的代码:
local function send(cons, x) coroutine.resume(cons, x) end local function receive() return coroutine.yield() end local function consumer() return coroutine.create( function(x) while true do io.write(x, '\n') -- coroutine.yield() 返回 coroutine.resume()的额外参数 x = receive() end end ) end function producer(cons) while true do local x = io.read() -- 创建新值 send(cons, x) -- 提供新值 end end producer(consumer())与作者的示例的不同之处在于
producer将值发送到consumer上,并且receive在write之后执行。进一步阅读:https://www.lua.org/pil/9.2.html。