首页 > 其他 > 详细

lua的corroutine学习

时间:2015-04-03 17:12:37      阅读:140      评论:0      收藏:0      [点我收藏+]

lua的corroutine学习

function receive (prod)
        local status, value = coroutine.resume(prod)
        return value
end

function send (x)
        coroutine.yield(x)
end

function producer ()
        return coroutine.create( function ()
                while true do
                        local x = io.read()
                        send(x)
                end
        end)
end

function filter (prod)
        return coroutine.create( function ()
                local line = 1
                while true do
                        local x = receive(prod)
                        x = string.format("%5d %s", line, x)
                        send(x)
                        line = line + 1
                end
        end)
end

function consumer (prod)
        while true do
                local x = receive(prod)
                io.write(x, "\n")
        end
end

p = producer()  -->creates a coroutine p, which yield after read a line from stdio agin and agin
f = filter(p)   -->creates a coroutine f, which resume the p at first and yeild after the string processed
consumer(f)     -->resumes the coroutine f, and writes the string f processed

 

lua的corroutine学习

原文:http://www.cnblogs.com/pied/p/3167271.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!