Lua协程-生产者、消费者问题

实现1

local queue = {}

function producer()  
    return coroutine.create(function(count)
        local count = count or 1
        local c = 0
        while true do
            if c < count then
                local ele = math.random(1, 10)
                table.insert(queue, ele)
                print(string.format('produce:%s.', ele))
                c = c + 1
            else
                print(string.format('produce %s elements.', c))
                c = 0
                count = coroutine.yield() or count
            end
        end
    end)
end

function consumer()  
    return coroutine.create(function(count)
        local count = count or 1
        local c = 0
        while true do
            if c < count and #queue > 0 then
                ele = table.remove(queue, 1)
                c = c + 1
                print(string.format('consume:%s', ele))
            else
                print(string.format('consume %s elements.', c))
                c = 0
                count = coroutine.yield() or count
            end 
        end
    end)
end

MainLoop = {taskqueue={}}  
function MainLoop.spawn(co, ...)  
    MainLoop.taskqueue[co] = {...}
end

function MainLoop.joinall()  
    local co, args
    while true do
        co, args = next(MainLoop.taskqueue, co)
        if co ~= nil then
            status, info = coroutine.resume(co, table.unpack(args))
            if status == false then
                print(info)
                MainLoop.taskqueue[co] = nil
            end
        end
        if not next(MainLoop.taskqueue) then break end
    end
end

MainLoop.spawn(producer(), 3)  
MainLoop.spawn(consumer(), 3)  
MainLoop.joinall()

Programming in Lua上的实现

function producer()  
    return coroutine.create(function ()
        while true do
            local ele = math.random(1, 10)
            print(string.format("produce:%s", ele))
            coroutine.yield(ele)
        end
    end)
end

function consumer(prod)  
    while true do
        local status, ele = coroutine.resume(prod)
        if not status then break end
        print(string.format("consume:%s", ele))
    end
end

function filter(prod)  
    return coroutine.create(function ()
        local c = 0
        while true do
            local status, ele = coroutine.resume(prod)
            if not status then break end
            c = c + 1
            coroutine.yield(string.format("%5d-%s", c, ele))
        end
    end
    )
end

consumer(filter(producer()))

感谢浏览tim chow的作品!

如果您喜欢,可以分享到: 更多

如果您有任何疑问或想要与tim chow进行交流

可点此给tim chow发信

如有问题,也可在下面留言: