生产者和消费者问题:
当协程调用yield时,从一个悬而未决的resume中返回。
简单的协程练习:
function receive() local status,value = coroutine.resume(producer) return status,value end function send(x) coroutine.yield(x) end producer = coroutine.create( function() local x = 0 while true do x = x+1 if(x > 10) then break end send(x) end end) local status,res repeat status,res = receive() print(status, res) until(nil == res)
输出:
>lua -e "io.stdout:setvbuf 'no'" "1.lua"
true 1
true 2
true 3
true 4
true 5
true 6
true 7
true 8
true 9
true 10
true nil
>Exit code: 0
这种模式被称为消费者驱动模式。
过滤器filter是一种位于生产者和消费者之间的处理函数,用于对数据进行变换。它既是一个生产者又是消费者,他唤醒生产者产生new value,然后又将变换后的值传给消费者。
表示自己写的代码,出问题了:
function receive(prod) local value = coroutine.resume(prod) return value end function send(x) coroutine.yield(x) end x = 0 function producer() return coroutine.create( function() x = x + 1 print(sting.format("producer:%d. ",x)) return x end) end function filter(prod) return coroutine.create( function() local x = receive(prod) x = string.format("Add:%d",x) send(x) end ) end function consumer(prod) repeat res = receive(prod) print(res) until (nil == res) end p = producer() f = filter(p) print(x) consumer(f)
晚上回去看看怎么回事。