gpt4 book ai didi

lua - 放弃协程

转载 作者:行者123 更新时间:2023-12-04 05:21:28 24 4
gpt4 key购买 nike

在Lua 5.1中,永远不要让协程正常结束有多糟糕?换句话说,如果协程产生但我从未恢复过,它会在程序完成之前留下很多状态吗?

cor=coroutine.wrap(somefunc)

while true do
done=cor()
if done then -- coroutine exited with "return true"
break
else -- coroutine yielded with "coroutine.yield(false)"
if some_condition then break end
end
end

function somefunc()
-- do something
coroutine.yield(false)
-- do some more
return true
end

根据上面伪代码中的 some_condition ,协程可能永远不会恢复,因此可能永远不会正确“结束”。

我可以不必对数十个协程执行此操作,而不必担心吗?将协程保持在这种状态是否安全?这个很贵吗?

最佳答案

垃圾收集器可以轻松确定协程不可达并进行收集。我不知道是否有任何文档说明会发生这种情况,但是我尝试了“经验方法”:

虽然是真的
本地cor = coroutine.wrap(function()coroutine.yield(false)结束)
cor()
结尾

内存使用量并没有随着时间的推移而增长。

编辑:谷歌说:

There is no explicit operation for deleting a Lua coroutine; like any other value in Lua, coroutines are discarded by garbage collection.(PDF中的第4页)

关于lua - 放弃协程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3642808/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com