协同进程实现生产者消费者

    xiaoxiao2022-07-13  163

    代码及注释如下,使用print函数打印值和行号,可以看到代码的运行路径

    --[[ resume协程,如果协程执行的过程中调用yield函数,则resume函数返回yield的参数 ]] function receive(prod) local status, value = coroutine.resume(prod) print(value, debug.getinfo(1).currentline) return value end --[[ 若是在一个协程里调用yield函数,则会挂起当前协程 ]] function send(x) print(x, debug.getinfo(1).currentline) coroutine.yield(x) end --[[ 创建一个协程;生产、停止生产、将生产的东西发给消费者 ]] function producer() return coroutine.create(function () while true do local x = io.read() -- 生产商品 print(x, debug.getinfo(1).currentline) send(x) --停止生产、返回商品 end end) end --[[ 消费者是一个循环,当需要消费的时候,就唤醒生产者 然后将商品打印出来 ]] function consumer(prod) while true do local x = receive(prod) -- 从生产者那里获得商品 print(x, debug.getinfo(1).currentline) io.write(x, "\n") end end consumer(producer()) --[[ 运行结果: hello -- 输入 hello 27 hello 16 hello 7 hello 41 hello -- io.write输出 ]]

    理解:

    生产者是一个协程,将生产者的执行过程传给消费者“consumer(producer())”,消费者什么时候商品需要就调用receive函数,让生产者生产,然后消费掉。生产者被消费者唤醒之后“resume”,就开始生产"io.read",生产完成之后,就马上停工"yield",将商品给消费者"yield之后,商品由resume函数返回"。

    最新回复(0)