开发者

Abandoning coroutines

开发者 https://www.devze.com 2023-01-14 05:25 出处:网络
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 comp

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?


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)

0

精彩评论

暂无评论...
验证码 换一张
取 消