放弃协程

在Lua 5.1中,如果永远不让协同程序正确结束,会有多糟糕的后果?换句话说,如果一个协程 yield,但我从未 resume 它,那么它会一直保留大量状态直到程序结束吗?

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,协同程序可能永远不会被 resume,因此可能永远无法正确“结束”。

我可以这样做数十个 coroutines 而无需担心吗?让协程保持这种状态是安全的吗?是贵的吗?

原文链接 https://stackoverflow.com/questions/3642808

点赞
stackoverflow用户436275
stackoverflow用户436275

垃圾回收器可以轻易地确定协程是不可达的并进行回收。我不知道文档中是否有说明会发生这种情况,但我用“经验主义方法”试过:

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

随着时间的推移,内存使用情况没有增加。

编辑: 谷歌表示:

Lua 协程没有显式的删除操作;与 Lua 中的任何其他值一样,协程通过垃圾回收进行丢弃。 (PDF 的第 4 页)

2010-09-04 15:21:42