Thunk memory leak as a result of map function

2019-06-16 16:09发布

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

2条回答
我想做一个坏孩纸
2楼-- · 2019-06-16 16:48

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.

查看更多
相关推荐>>
3楼-- · 2019-06-16 16:52

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        
查看更多
登录 后发表回答