Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abandoning coroutines

Tags:

coroutine

lua

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?

like image 649
proFromDover Avatar asked Sep 04 '10 15:09

proFromDover


1 Answers

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)

like image 186
Uli Schlachter Avatar answered Nov 13 '22 12:11

Uli Schlachter