lua生产者-消费者学习

继续看第九章,不过这次是看英文版,读起来没啥难度,学习一点代码:

典型的生产者-消费者模型:

produter生成Salt,consumer消费掉:

--线程
local function producer()
	return coroutine.create(
	function(salt)
		local t = {1,2,3}
		for i = 1,#t do
			salt = coroutine.yield(t[i] + salt)
			--salt是consumer传回来的返回值
			print('producer salt',salt)
		end
	end
	)
end

function consumer(prod)
	local salt = 10
	while true do
		local running ,product = coroutine.resume(prod, salt) --salt是producer coroutine.yield的返回值,salt作为producer的返回值设置给salt
		if running == false then
			return
		else
			print('running:',running,',produtc:',product,',salt:',salt)
			salt = salt*salt
		end
	end
end

consumer(producer())



运行结果:

>lua -e "io.stdout:setvbuf 'no'" "cor.lua" 
running: true ,produtc: 11 ,salt: 10
running: true ,produtc: 102 ,salt: 100
running: true ,produtc: 10003,salt: 10000
running: true ,produtc: nil ,salt: 100000000
>Exit code: 0

lua的函数返回值还是很蛋疼的,看了我好久才搞明白 

你可能感兴趣的:(Lua)