2010-09-04 66 views
7

在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,协程可能永远不会恢复,因而可能永远正确“结束”。

我可以这样做几十个协程而不必担心吗?在这种状态下保留协程是否安全?这个很贵吗?

+4

我不知道Lua中所有,但如果我是你的话,我想知道更大问题:你如何确定你是否在泄漏记忆(或者当你说“昂贵”时感兴趣的任何内容)?例如,如果有一个工具,那么你可以自己回答这个问题。 – 2010-09-04 15:19:27

+0

这将用于评估内存消耗元素,但我也想知道它是否安全。即它会造成后来无法预料的问题吗? – proFromDover 2010-09-05 03:09:13

回答

17

垃圾收集器可以很容易地确定协程无法访问并收集它。我不知道是否有任何文档的状态,这会发生,但我试过“经验方法”:

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

内存使用量并没有随时间增长。

编辑:谷歌表示:

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

+0

PDF很棒,谢谢你指出。 – proFromDover 2010-09-05 03:06:28