协同进程实现生产者消费者

这篇博客详细介绍了如何使用Lua的协程实现生产者消费者模式。通过代码示例和注释,展示了生产者如何作为协程运行,并在消费者需要时通过`receive`函数调用,生产者在完成生产后通过`yield`暂停,将产品传递给消费者,而消费者通过`resume`函数接收并消费商品。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码及注释如下,使用print函数打印值和行号,可以看到代码的运行路径


--[[
resume协程,如果协程执行的过程中调用yield函数,则resume函数返回yield的参数
]]
function receive(prod)
	local status, value = coroutine.resume(prod)
	print(value,  debug.getinfo(1).currentline)
	return value
end


--[[
若是在一个协程里调用yield函数,则会挂起当前协程
]]
function send(x)
    print(x,  debug.getinfo(1).currentline)
	coroutine.yield(x)
end

--[[
创建一个协程;生产、停止生产、将生产的东西发给消费者
]]
function producer()
	return coroutine.create(function ()
		while true do
			local x = io.read() -- 生产商品
			print(x,  debug.getinfo(1).currentline)
			send(x) --停止生产、返回商品
		end
	end)
end


--[[
消费者是一个循环,当需要消费的时候,就唤醒生产者
然后将商品打印出来
]]
function consumer(prod)
	while true do
		local x = receive(prod) -- 从生产者那里获得商品
		print(x,  debug.getinfo(1).currentline)
		io.write(x, "\n")
	end
end


consumer(producer())

--[[
运行结果:
hello -- 输入
hello	27
hello	16
hello	7
hello	41
hello -- io.write输出
]]

理解:

生产者是一个协程,将生产者的执行过程传给消费者“consumer(producer())”,消费者什么时候商品需要就调用receive函数,让生产者生产,然后消费掉。生产者被消费者唤醒之后“resume”,就开始生产"io.read",生产完成之后,就马上停工"yield",将商品给消费者"yield之后,商品由resume函数返回"。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值