Thunk memory leak as a result of map function

陌路散爱 提交于 2019-12-23 08:49:45

问题


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

回答1:


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        



回答2:


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.



来源:https://stackoverflow.com/questions/6630782/thunk-memory-leak-as-a-result-of-map-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!