放弃协程
在 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,协程可能永远不会恢复,因此可能永远不会正确“结束”。
我可以对数十个协程执行此操作而不必担心吗?将协程置于这种状态是否安全?是不是很贵?
How bad is it in Lua 5.1 to never let a coroutine properly end? In other words, if a coroutine yields but I never resume it, does it leave a lot of state lying around until program completion?
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
Depending on some_condition in the pseudocode above, the coroutine might never be resumed, and thus might never properly "end".
Could I do this to dozens of coroutines without having to worry? Is it safe to leave coroutines in this state? Is it expensive?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
垃圾收集器可以轻松确定协程不可达并对其进行收集。我不知道是否有任何文档指出这种情况会发生,但我尝试了“经验方法”:
内存使用量不会随着时间的推移而增长。
编辑: Google 说:
没有明确的删除Lua协程的操作;与 Lua 中的任何其他值一样,协程会被垃圾回收丢弃。(PDF 中的第 4 页)
The garbage collector can easily determine that the coroutine is unreachable and collect it. I don't know if any of the docs state that this will happen, but I tried the "empirical method":
Memory usage did not grow over time.
Edit: Google says:
There is no explicit operation for deleting a Lua coroutine; like any other value in Lua, coroutines are discarded by garbage collection. (Page 4 in the PDF)