The Death of Finalizers

George Russell ger at tzi.de
Tue Oct 22 08:16:19 EDT 2002


Simon Peyton-Jones wrote:
> 
> | In the meantime, I'm glad we have got a new function
> |    atomicModifyIORef
> | which I for one will use, when it gets into GHC's regular release.
> 
> Just before this gets out of the door... any chance of calling it
> 
>         modifyIORef
> 
> and documenting that it's atomic

My vote goes for

modifyIORef :: IORef a -> (a -> (a,b)) -> IO b
modifyIORef_ :: IORef a -> (a -> a) -> IO a

modifyIORef_ ioRef fn = modifyIORef ioRef (\ a0 -> let a1 = fn a0 in (a1,a1))

The names are similar to those of GHC's modifyMVar and modifyMVar_.
I think there's some sense in providing modifyIORef_ as well as 
modifyIORef, as I think for some implementations it will be even faster,
since it's unnecessary to create thunks for (fst (fn a0)) and 
(snd (fn a0)).  But you lot know a lot more about writing Haskell 
compilers than I do . . .

Thus you can implement a counter returning integers 1,2,3,...
via

   newCounter :: IO (IO Integer)
   newCounter = do
      ioRef <- newIORef 0
      return (modifyIORef_ ioRef (+1))

I don't think it's necessary for the name to include "atomic".
We are unlikely ever to want a non-atomic version of atomicModifyIORef,
especially as such a thing would be quite dangerous, and you can roll
your own from readIORef and writeIORef.



More information about the FFI mailing list