在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
Run Code Online (Sandbox Code Playgroud)
根据上面伪代码中的some_condition,协程可能永远不会被恢复,因此可能永远不会正确地"结束".
我可以这样做几十个协同程序而不必担心吗?将协同程序置于此状态是否安全?这个很贵吗?
Uli*_*ter 18
垃圾收集器可以很容易地确定协程无法访问并收集它.我不知道是否有任何文件表明会发生这种情况,但我尝试了"经验方法":
while true do local cor = coroutine.wrap(function() coroutine.yield(false) end) cor() end
内存使用率并未随着时间的推移而增
编辑:谷歌说:
删除Lua协程没有明确的操作; 与Lua中的任何其他值一样,协同程序被垃圾收集丢弃.(PDF中的第4页)