lua之coroutine

本文介绍了Lua中的协程coroutine,包括如何通过coroutine.create创建,使用coroutine.resume启动和挂起,以及coroutine.yield的使用方法。通过示例展示了如何实现生产者与消费者的模式,揭示了协程在异步编程中的潜力。

coroutine

lua天然支持coroutine, coroutine属于协程而非多线程。
通过coroutine.create来创建一个协程,然后调用coroutine.resume启动,当函数中遇到coroutine.yield时协程将会被挂起直到再次调用coroutine.resume。

local co = coroutine.create(function(...)
print(...)
end)

print("==start==")
coroutine.resume(co,"coroutine")
print("==end==")

执行结果

==start==
coroutine
==end==

通过上面的例子我们可以发现当调用完coroutine.create返回的coroutine并不会直接启动,必须通过调用coroutine.resume来启动

resume

resume不仅可以可以将函数的参数传递给create的协程,而且还可以传递给yield。

local co = coroutine.create(function(...) --function test(...)
	print(...)
	return coroutine.yield(1)
end)

print("==start==")
print(coroutine.resume(co,"start"))
print(coroutine.resume(co,"end"))
print("==end==")

执行结果

==start==
start
true	1
true	end
==end==

第一次调用resume的时候,所带的参数"start"传递给了test函数。第二次调用resume的时候,所带的参数传递给了yield的返回值

yield

yield必须要在coroutine中调用,否则将会报错.yield的参数将会传递给resume,即resume的第二个以及后面的返回值。

示例代码-- 生产者与消费者

通过yield和resume的配合可以实现出很多高级的功能,比如生产者与消费者。以及async/await机制等.

local newProductor

function productor()
    for i=1,10 do
         send(i)
    end
end

function consumer()
     for i=1,10 do
          local i = receive() 
          print("consumer",i)
     end
end

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

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

newProductor = coroutine.create(productor)
consumer()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值