Lua: coroutine

function producer()
    local i = 0
    print(coroutine.running())
    while true do
        i = i + 1
        if i > 5 then
            error('out of number')
        end
        print('In Producer>> coroutine(co) status:', coroutine.status(co))
        coroutine.yield(i)
    end
end

function consumer(co)
    print(coroutine.running())
    while true do
        local status, value = coroutine.resume(co)
        if status then
            print('value: ', value)
        else
            print('coroutine error: ', value)
            break
        end
        os.execute("sleep " .. 1)
        print('In Consumer>> coroutine(co) status:', coroutine.status(co))
    end
end

print(coroutine.running())
co = coroutine.create(producer)
print(coroutine.isyieldable(co))
consumer(co)

 

posted @ 2022-05-29 17:46  ascertain  阅读(23)  评论(0编辑  收藏  举报