Lua协程

1. 协程是什么?

简单的说可以理解为C++里面的线程(thread),但是和线程不一样的是,多线程可以并发执行,而多个协程在同一时间却只能有一个在工作。

协程的状态有四种:

  • 挂起(suspended)--- 刚创建的协程是这个状态
  • 运行(running) --- 不解释
  • 死亡(dead) --- 程序运行结束
  • 正常(normal) --- 这个状态比较特殊,处于运行过程中使用yield暂停自己的状态

2. 协程的创建

coroutine.create

3. 协程的运行

coroutine.resume

4. 获取状态

coroutine.status

5. 协程的重点:yield函数的使用

lua协程的一项最重要的机制就是通过resume-yield来实现数据的交换
lua 通过resume传入参数,而通过yield传出参数

例子:

local co = coroutine.create(function (a, b, c)
	print(a, b, c) --- 接收到的参数
	coroutine.yield(a + b, a + c, b + c)  --- 传出参数
end)

print(coroutine.resume(co, 4, 5, 6))

6. 协程的应用

经典案例: 生产者-消费者模式

function receive( )
	local status, value = coroutine.resume(producer)
	print('receive', value)
	return value
end

function send( value )
	print('send', value)
	coroutine.yield(value)
end


producer = coroutine.create(
	function ( )
		index = 0
		while true do
			local x = index;
			index = index + 1
			send(x)
		end
	end
)

consumer = coroutine.create(
	function (  )
		while true do
			local value = receive()
			print(value)
		end
	end
)

while true do
	coroutine.resume(producer)
	coroutine.resume(consumer)
end

posted @ 2015-10-29 16:21  zyh_think  阅读(374)  评论(0编辑  收藏  举报