Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thunk memory leak as a result of map function

I am writing a multi-threaded program that makes quite a use of mvars; in this case I have a thread that periodically changes list inside an mvar. Unfortunately, there is a thunk memory leak. There seems to be aproblem that the 'map id' (in real program I use something else than id) function leaks. I just cannot find a way how to avoid that - I was playing with 'seq' with no result. What is the right way to fix the leak?

upgraderThread :: MVar [ChannelInfo] -> IO ()
upgraderThread chanMVar = forever job
    where
        job = do
            threadDelay 1000
            vlist <- takeMVar chanMVar
            let reslist = map id vlist
            putMVar chanMVar reslist
like image 606
ondra Avatar asked Jul 08 '11 21:07

ondra


People also ask

What is the main cause of memory leaks?

A memory leak starts when a program requests a chunk of memory from the operating system for itself and its data. As a program operates, it sometimes needs more memory and makes an additional request.

What causes memory leak in Linux?

A memory leak occurs when memory is allocated but not freed when it is no longer needed. Leaks can obviously be caused by a malloc() without a corresponding free() , but leaks can also be inadvertently caused if a pointer to dynamically allocated memory is deleted, lost, or overwritten.

Does exit cause memory leaks?

Not under modern operating systems, no. The OS automatically collects all the memory when the process dies. In fact freeing memory can actually be detrimental for the performance if the program is exiting anyway.


1 Answers

After a few more tries, this one seems to work:

upgraderThread chanMVar = forever job
    where
        job = do
            threadDelay 1000
            vlist <- takeMVar chanMVar
            let !reslist = strictList $ map id vlist
            putMVar chanMVar reslist

        strictList xs = if all p xs then xs else []
            where p x = x `seq` True        
like image 141
ondra Avatar answered Sep 20 '22 14:09

ondra