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
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With