[Haskell-cafe] IORefs and weak pointers

Patai Gergely patai_gergely at fastmail.fm
Mon Nov 2 15:04:19 EST 2009

> Could mkWeakPair do what you want?
> http://haskell.org/ghc/docs/latest/html/libraries/base/System-Mem-Weak.html#v:mkWeakPair
No, it's just a convenience function that doesn't help much, because the
value already refers to the IORef anyway.

Here's a minimal example to illustrate the problem:

import Data.IORef
import Data.Maybe
import System.Mem
import System.Mem.Weak

main = do
  ref <- newIORef 42
  ptr <- mkWeak ref 21 Nothing
  print . isNothing =<< deRefWeak ptr
  print =<< readIORef ref

Depending on whether you compile with optimisations, the weak reference
might be reported dead, even though the IORef is alive and kicking.
Switching to mkWeakPair (or just mentioning ref in the value somehow)
doesn't affect that.

> Or are you trying to do something else?
The goal is to create mutable objects whose update codes are tracked by
the main program, but they can be thrown out when all the other
references to the objects are lost. Creating weak pointers with MutVar#s
seems to do the trick, but I'm not confident if it is a solution I can


http://www.fastmail.fm - A fast, anti-spam email service.

More information about the Haskell-Cafe mailing list