接触lua的协同程序

lua中没有真正的多线程,用了协同程序代替,照例来个demo看看,如下:

 

#!usr/bin/env lua function receive(prod) local status, value = coroutine.resume(prod) return value end function send(v) coroutine.yield(v) end -- product function producer() return coroutine.create(function() while true do local v =io.read() send(v) end end) end --consumer function consumer(prod) while true do local x = receive(prod) io.write(x, "/n") end end function filter(prod) return coroutine.create(function() for line = 1, math.huge do local v = receive(prod) v = string.format("%5d %s", line, v) send(v) end end) end --main 协同程序 p = producer() f = filter(p) consumer(f)

 

 

就一个生产者--消费装模型,看看就行。

你可能感兴趣的:(多线程,function,filter,lua)