协同进程+过滤器实现生产者消费者

这篇博客通过Lua的协程(coroutine)展示了如何实现经典的生产者消费者问题。代码中详细注释了每个步骤,利用print函数跟踪运行流程,帮助理解协同进程在解决此类问题中的应用。

摘要生成于 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) -- 参数是filter协程
		print(x,  debug.getinfo(1).currentline)
		io.write(x, "\n")
	end
end

function filter(prod)
	return coroutine.create(function ()
		local line = 1
		while true do
			local x = receive(prod)
			print(x,  debug.getinfo(1).currentline)
			x = string.format("%5d %s", line, x)
			send(x)
			line = line + 1
		end
	end)
end


--[[
调用producer()返回一个协程
调用filter(prod)返回一个协程
执行consumer函数

1.consumer调用receiver函数
2.filter协程开始执行
3.producer协程开始执行
4.producer协程挂起
5.filter协程挂起
6.返回到consumer的receiver函数
]]
consumer(filter(producer()))

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值