Reputation: 9331
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
Upvotes: 7
Views: 779
Reputation: 31
Besides the space leak, the earlier version may also have a "time leak" in that the unevaluated thunks placed into the mvar may get evaluated by the receiving thread instead of the sending one, possibly destroying any intended parallelism.
Upvotes: 3
Reputation: 9331
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
Upvotes: 3