coroutine我自己的理解是伪中断。在调用coroutine.yeild时就会自动调用正在wait中的coroutine.resume。并且会把yeild里面的参数按顺序作为resume的第二、三等返回值返回。resume第一返回值是coroutine的状态。
function receive(prod) local status, value = coroutine.resume(prod) return value end function send(x) coroutine.yield(x) end function producer() local i = 0 return coroutine.create(function() while true do local x = i i = i + 1 send(x) end end) end function filter(prod) return coroutine.create(function() for line = 1, math.huge do local x = receive(prod) x = string.format("%5d %s", line, x) send(x) end end) end function consumer(prod) while true do local x = receive(prod) print("received:" .. x) end end consumer(filter(producer()))
抄袭下一个现成的代码,这个代码打印如下。
1 0
2 1
...
原理就是先执行producer,filter 创建couroutine,consumer到receive(A)卡死在resume上,同时couroutine触发了filter里面的receive(B),couroutine触发了producer的send(0),yeild这时就执行到了最近的receive(B)中的resume并且把0传给了value。filter继续执行,将 1 0 传给send,这时send把值给receive(A),一个循环结束。
虽然这个看起来是多个函数之间的同步,但是实际上还是一个线程上的同步。主界面还是会卡死。so需要在线程中做这样的同步。