lua协程

本文介绍了 Lua 中协程的四种状态:挂起、运行、死亡和正常,并详细阐述了如何使用协程来实现生产者消费者问题。生产者负责产生新值,而消费者则负责消费这些值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一协程的状态

分为四种:
挂起(suspended):当创建一个协程时它便处于挂起状态,所以当我们创建协程时他不会自动执行,调用coroutine.yield时也是变成挂起状态
运行(running):调用coroutine.resume时便处于运行状态
死亡(dead):当协程运行结束之后便处于dead状态,而且无法返回
正常(normal):当一个协程a唤起另一个协程b,a变处于正常状态

co = coroutine.create(function()
    for i= 1,3 do
        coroutine.yield(i)
    end
end)
print(coroutine.resume(co))--true 1
print(coroutine.status(co))--suspended
print(coroutine.resume(co))--true 2
print(coroutine.status(co))--suspended
print(coroutine.resume(co))--true 3
print(coroutine.status(co))--suspended
print(coroutine.resume(co))--true
print(coroutine.status(co))--dead
print(coroutine.resume(co))--false

实现生产者消费者问题

生产者:不断产生新值
消费者:不断消费这些值

--唤醒生产者执行产生一个新值
function receive(producer)
    local status, value = coroutine.resume(producer)
    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()
        for line = 1,math.huge do
            local x= receive(prod)--接收新值
            x = string.format("%5d %s",line ,x)
            send(x)--将新值发送给消费者
        end
    end)
end
--消费者
function consumer(prod)
    while true do
        local x = receive(prod)--接收新值
        io.write(x,"\n")
    end
end

p = producer()
f = filter(p)
consumer(f)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值