Lua 中被遗弃的协程发生了什么
What happens to abandoned coroutine in Lua
我想知道这个例子中的协程会发生什么:
function powersOfTwo(i)
coroutine.yield(i)
powersOfTwo(2*i)
end
function iterator()
return coroutine.wrap(function () powersOfTwo(1) end)
end
for power in iterator() do
print(power)
if power > 1000 then break end
end
协程没有完成它的代码。它是垃圾收集的吗?
The coroutine does not finish its code. Is it garbage collected?
是的,它是 garbage-collected,因为在循环执行完成后没有对协程的引用。 这涉及协程的事实并不做出改变;如果 iterator()
返回一个闭包,它会是 garbage-collected 都是一样的。
您可以使用 collectgarbage
:
来验证这一点
-- Declare functions, which won't be garbage-collected as they're in the global table
function collectgarbage_full()
for _ = 1, 10 do -- Run multiple cycles to ensure that all garbage is collected even if the generational GC of Lua 5.2 or later is used
collectgarbage"collect"
end
end
function powersOfTwo(i)
coroutine.yield(i)
powersOfTwo(2*i)
end
function iterator()
return coroutine.wrap(function() powersOfTwo(1) end)
end
-- Count non-garbage used memory
collectgarbage_full()
local used = collectgarbage"count"
-- Now use the iterator, creating a garbage coroutine
for power in iterator() do
print(power)
if power > 1000 then break end
end
-- Collect garbage, compare used memory against used memory before the garbage coroutine
collectgarbage_full()
if used < collectgarbage"count" then
error"Garbage coroutine was not collected!"
end
print"Coroutine was garbage-collected."
您应该看到以下输出:
1
2
4
8
16
32
64
128
256
512
1024
Coroutine was garbage-collected.
我想知道这个例子中的协程会发生什么:
function powersOfTwo(i)
coroutine.yield(i)
powersOfTwo(2*i)
end
function iterator()
return coroutine.wrap(function () powersOfTwo(1) end)
end
for power in iterator() do
print(power)
if power > 1000 then break end
end
协程没有完成它的代码。它是垃圾收集的吗?
The coroutine does not finish its code. Is it garbage collected?
是的,它是 garbage-collected,因为在循环执行完成后没有对协程的引用。 这涉及协程的事实并不做出改变;如果 iterator()
返回一个闭包,它会是 garbage-collected 都是一样的。
您可以使用 collectgarbage
:
-- Declare functions, which won't be garbage-collected as they're in the global table
function collectgarbage_full()
for _ = 1, 10 do -- Run multiple cycles to ensure that all garbage is collected even if the generational GC of Lua 5.2 or later is used
collectgarbage"collect"
end
end
function powersOfTwo(i)
coroutine.yield(i)
powersOfTwo(2*i)
end
function iterator()
return coroutine.wrap(function() powersOfTwo(1) end)
end
-- Count non-garbage used memory
collectgarbage_full()
local used = collectgarbage"count"
-- Now use the iterator, creating a garbage coroutine
for power in iterator() do
print(power)
if power > 1000 then break end
end
-- Collect garbage, compare used memory against used memory before the garbage coroutine
collectgarbage_full()
if used < collectgarbage"count" then
error"Garbage coroutine was not collected!"
end
print"Coroutine was garbage-collected."
您应该看到以下输出:
1
2
4
8
16
32
64
128
256
512
1024
Coroutine was garbage-collected.