[Haskell-cafe] Re: threads + IORefs = Segmentation fault?

Simon Marlow simonmarhaskell at gmail.com
Fri Feb 8 05:46:25 EST 2008

David Roundy wrote:

> I'm working on some new progress-reporting code for darcs, and am getting
> segmentation faults!  :( The code uses threads + an IORef global variable
> to do this (with lots of unsafePerformIO).  So my question for the gurus
> who know more about this than I do:  is this safe? I thought it would be,
> because only one thread ever modifies the IORef, and the others only read
> it.  I don't really care if they read a correct value, as long as they
> don't segfault.
> The code (to summarize) looks like:
> {-# NOINLINE _progressData #-}
> _progressData :: IORef (Map String ProgressData)
> _progressData = unsafePerformIO $ newIORef empty
> updateProgressData :: String -> (ProgressData -> ProgressData) -> IO ()
> updateProgressData k f = when (progressMode) $ modifyIORef _progressData (adjust f k)
> setProgressData :: String -> ProgressData -> IO ()
> setProgressData k p = when (progressMode) $ modifyIORef _progressData (insert k p)
> getProgressData :: String -> IO (Maybe ProgressData)
> getProgressData k = if progressMode then lookup k `fmap` readIORef _progressData
>                                     else return Nothing

(I'm a bit behind with haskell-cafe, sorry for not seeing this sooner...)

Yes, that should all be fine, because the IORef is only modified from one 
thread, and read from the other(s).   If you were modifying the IORef from 
more than one thread you would need to use atomicallyModifyIORef, or MVars.


More information about the Haskell-Cafe mailing list