Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua table memory leak?

I have a memory leak issue about the usage of lua table, the code is below:

function workerProc()
    -- a table holds some objects (userdata, the __gc is implememted correctly)
    local objs = {createObj(), createObj(), ...}
    while isWorking() do
        -- ...
        local query = {unpack(objs)}
        repeat
            -- ...
            table.remove(query, queryIndex)
        until #query == 0
        sleep(1000)
    end
end

the table objs is initialized with some userdata objects and these objects are always available in the while loop so no gc will performed on these objs. In the while loop the query table is initialize with all the elements from objs (use unpack function). While running the script I found that the memory keeps increasing but when I comment out local query = {unpack(objs)} it disappears.

I don't think this piece of code have memory leak problem cause the query var is local and it should be unavailable after each iteration of while loop, but the fact is. Anybody know why the memory is swallowed by that table?

like image 850
Kery Avatar asked Nov 22 '13 07:11

Kery


1 Answers

Judging from your code example, the likely explanation for what you are seeing is perhaps the gc doesn't get a chance to perform a full collection cycle while inside the loop.

You can force a collection right after the inner loop using collectgarbage() and see if that resolves the memory issue:

while isWorking() do
    -- ..
    local query = {unpack(objs)}
    repeat
        -- ..
        table.remove(query, queryIndex)
    until #query == 0
    collectgarbage()
    sleep(1000)
end

Another possibility is to move local query outside the loop and create the table once instead of creating a new table on every iteration in the outter loop.

like image 97
greatwolf Avatar answered Oct 18 '22 04:10

greatwolf