放弃协程

发布于 2024-09-17 08:47:27 字数 569 浏览 1 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

败给现实 2024-09-24 08:47:28

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

while true do
  local cor = coroutine.wrap(function() coroutine.yield(false) end)
  cor()
end

内存使用量不会随着时间的推移而增长。

编辑: 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":

while true do
  local cor = coroutine.wrap(function() coroutine.yield(false) end)
  cor()
end

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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文