7

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
ondra
  • 9,122
  • 1
  • 25
  • 34

2 Answers2

3

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        
ondra
  • 9,122
  • 1
  • 25
  • 34
  • 6
    The pattern you're using in `strictList` is generalized by `deepseq`; see http://hackage.haskell.org/packages/archive/deepseq/latest/doc/html/Control-DeepSeq.html – acfoltzer Jul 08 '11 at 23:10
3

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.

solrize
  • 31
  • 1