lua之coroutine

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()

猜你喜欢

转载自blog.csdn.net/scdnshijiemengxiang/article/details/128909220