-2

我有最小的代码,有两个问题,虽然现在只有一个很重要。那是我的内存泄漏几乎为零代码。另一个是过剩迫使我使用 unsafePerformIO 只是为了让我可以在回调中使用一个 IORef(没有参数,所以它需要是全局的)。是的,我从那个教程中复制了一些。

(不用担心间距):

{-# LANGUAGE ExistentialQuantification,
             TemplateHaskell,
             BangPatterns,
             RecursiveDo,
             GeneralizedNewtypeDeriving,
             MagicHash #-}
module Game
( Game (..)
) where
import Entity
import Util
import GUtil
import Resources
import Control.Lens
import Control.Monad.State.Lazy
import Graphics.Rendering.OpenGL hiding (get)
import Graphics.UI.GLUT hiding (get)
import Data.IORef
import qualified System.IO.Unsafe --I'm so so sorry, it's to initialize some global references since the callbacks don't have parameters

data Game = Game
          { _root :: Entity
          , _resources :: [Resource]
          }
$(makeLenses ''Game) 

gameRef :: IORef Game
gameRef = System.IO.Unsafe.unsafePerformIO (newIORef $ (Game (Entity ENull EDataNull []) []))

main :: IO ()
main = do
    (progname, _) <- getArgsAndInitialize
    createWindow "Hello World"
    idleCallback $= doUpdateGame
    displayCallback $= display
    reshapeCallback $= Just reshape
    mainLoop
reshape s@(Size w h) = do
    viewport $= (Position 0 0, s)
    postRedisplay Nothing

display :: IO ()
display = do
    clear [ ColorBuffer ]
    flush

doUpdateGame :: Maybe (IO ())
doUpdateGame = Just $ do
                modifyIORef gameRef (snd . runState updateGame)
updateGame :: State Game ()
updateGame = do 
                return ()

在这一小段代码中,哪里有可能导致泄漏的问题?

4

1 回答 1

1

您不需要全局 unsafe IORef,只需使用部分应用程序。

粗略且未经测试的代码:

idleCallback $= (doUpdateGame someLocalIORef)

...

doUpdateGame :: IORef Game -> Maybe (IO ())
doUpdateGame gameRef = Just $ modifyIORef gameRef (snd . runState updateGame)

此外,似乎没有任何东西迫使它IORef被评估,所以这可能是空间泄漏。如果一些明显的严格性注释没有帮助,请尝试分析。

于 2013-06-10T04:10:14.007 回答