Tuesday, 4 March 2014

Coroutine in Lua - Consumer driven Producer-Consumer implementation

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

function receive()
    return coroutine.resume(co)
end

function consumer()
    while true do
        local _, task = receive()

        if(task == nil) then break end

        print("Processed item", task)
    end
end

co = coroutine.create(function ()
    local file = io.open("io.txt", "r")

    while true do
        local task = file:read("*line")

        if(task ~= nil) then
            send(task)
            print("waiting for consumer to signal")
        else
            break
        end
    end
end)

consumer()

No comments: