avoid Foreign.unsafePerformIO
[ghc-base.git] / GHC / Conc / Sync.lhs
1 \begin{code}
2 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
3 {-# OPTIONS_GHC -fno-warn-missing-signatures #-}
4 {-# OPTIONS_HADDOCK not-home #-}
5 -----------------------------------------------------------------------------
6 -- |
7 -- Module      :  GHC.Conc.Sync
8 -- Copyright   :  (c) The University of Glasgow, 1994-2002
9 -- License     :  see libraries/base/LICENSE
10 --
11 -- Maintainer  :  cvs-ghc@haskell.org
12 -- Stability   :  internal
13 -- Portability :  non-portable (GHC extensions)
14 --
15 -- Basic concurrency stuff.
16 --
17 -----------------------------------------------------------------------------
18
19 -- No: #hide, because bits of this module are exposed by the stm package.
20 -- However, we don't want this module to be the home location for the
21 -- bits it exports, we'd rather have Control.Concurrent and the other
22 -- higher level modules be the home.  Hence:
23
24 #include "Typeable.h"
25
26 -- #not-home
27 module GHC.Conc.Sync
28         ( ThreadId(..)
29
30         -- * Forking and suchlike
31         , forkIO        -- :: IO a -> IO ThreadId
32         , forkIOUnmasked
33         , forkOnIO      -- :: Int -> IO a -> IO ThreadId
34         , forkOnIOUnmasked
35         , numCapabilities -- :: Int
36         , numSparks      -- :: IO Int
37         , childHandler  -- :: Exception -> IO ()
38         , myThreadId    -- :: IO ThreadId
39         , killThread    -- :: ThreadId -> IO ()
40         , throwTo       -- :: ThreadId -> Exception -> IO ()
41         , par           -- :: a -> b -> b
42         , pseq          -- :: a -> b -> b
43         , runSparks
44         , yield         -- :: IO ()
45         , labelThread   -- :: ThreadId -> String -> IO ()
46
47         , ThreadStatus(..), BlockReason(..)
48         , threadStatus  -- :: ThreadId -> IO ThreadStatus
49
50         -- * TVars
51         , STM(..)
52         , atomically    -- :: STM a -> IO a
53         , retry         -- :: STM a
54         , orElse        -- :: STM a -> STM a -> STM a
55         , catchSTM      -- :: STM a -> (Exception -> STM a) -> STM a
56         , alwaysSucceeds -- :: STM a -> STM ()
57         , always        -- :: STM Bool -> STM ()
58         , TVar(..)
59         , newTVar       -- :: a -> STM (TVar a)
60         , newTVarIO     -- :: a -> STM (TVar a)
61         , readTVar      -- :: TVar a -> STM a
62         , readTVarIO    -- :: TVar a -> IO a
63         , writeTVar     -- :: a -> TVar a -> STM ()
64         , unsafeIOToSTM -- :: IO a -> STM a
65
66         -- * Miscellaneous
67         , withMVar
68         , modifyMVar_
69
70         , setUncaughtExceptionHandler      -- :: (Exception -> IO ()) -> IO ()
71         , getUncaughtExceptionHandler      -- :: IO (Exception -> IO ())
72
73         , reportError, reportStackOverflow
74
75         , sharedCAF
76         ) where
77
78 import Foreign hiding (unsafePerformIO)
79 import Foreign.C
80
81 #ifdef mingw32_HOST_OS
82 import Data.Typeable
83 #endif
84
85 #ifndef mingw32_HOST_OS
86 import Data.Dynamic
87 #endif
88 import Control.Monad
89 import Data.Maybe
90
91 import GHC.Base
92 import {-# SOURCE #-} GHC.IO.Handle ( hFlush )
93 import {-# SOURCE #-} GHC.IO.Handle.FD ( stdout )
94 import GHC.IO
95 import GHC.IO.Exception
96 import GHC.Exception
97 import GHC.IORef
98 import GHC.MVar
99 import GHC.Num          ( Num(..) )
100 import GHC.Real         ( fromIntegral )
101 import GHC.Pack         ( packCString# )
102 import GHC.Show         ( Show(..), showString )
103
104 infixr 0 `par`, `pseq`
105 \end{code}
106
107 %************************************************************************
108 %*                                                                      *
109 \subsection{@ThreadId@, @par@, and @fork@}
110 %*                                                                      *
111 %************************************************************************
112
113 \begin{code}
114 data ThreadId = ThreadId ThreadId# deriving( Typeable )
115 -- ToDo: data ThreadId = ThreadId (Weak ThreadId#)
116 -- But since ThreadId# is unlifted, the Weak type must use open
117 -- type variables.
118 {- ^
119 A 'ThreadId' is an abstract type representing a handle to a thread.
120 'ThreadId' is an instance of 'Eq', 'Ord' and 'Show', where
121 the 'Ord' instance implements an arbitrary total ordering over
122 'ThreadId's. The 'Show' instance lets you convert an arbitrary-valued
123 'ThreadId' to string form; showing a 'ThreadId' value is occasionally
124 useful when debugging or diagnosing the behaviour of a concurrent
125 program.
126
127 /Note/: in GHC, if you have a 'ThreadId', you essentially have
128 a pointer to the thread itself.  This means the thread itself can\'t be
129 garbage collected until you drop the 'ThreadId'.
130 This misfeature will hopefully be corrected at a later date.
131
132 /Note/: Hugs does not provide any operations on other threads;
133 it defines 'ThreadId' as a synonym for ().
134 -}
135
136 instance Show ThreadId where
137    showsPrec d t =
138         showString "ThreadId " .
139         showsPrec d (getThreadId (id2TSO t))
140
141 foreign import ccall unsafe "rts_getThreadId" getThreadId :: ThreadId# -> CInt
142
143 id2TSO :: ThreadId -> ThreadId#
144 id2TSO (ThreadId t) = t
145
146 foreign import ccall unsafe "cmp_thread" cmp_thread :: ThreadId# -> ThreadId# -> CInt
147 -- Returns -1, 0, 1
148
149 cmpThread :: ThreadId -> ThreadId -> Ordering
150 cmpThread t1 t2 =
151    case cmp_thread (id2TSO t1) (id2TSO t2) of
152       -1 -> LT
153       0  -> EQ
154       _  -> GT -- must be 1
155
156 instance Eq ThreadId where
157    t1 == t2 =
158       case t1 `cmpThread` t2 of
159          EQ -> True
160          _  -> False
161
162 instance Ord ThreadId where
163    compare = cmpThread
164
165 {- |
166 Sparks off a new thread to run the 'IO' computation passed as the
167 first argument, and returns the 'ThreadId' of the newly created
168 thread.
169
170 The new thread will be a lightweight thread; if you want to use a foreign
171 library that uses thread-local storage, use 'Control.Concurrent.forkOS' instead.
172
173 GHC note: the new thread inherits the /masked/ state of the parent 
174 (see 'Control.Exception.mask').
175
176 The newly created thread has an exception handler that discards the
177 exceptions 'BlockedIndefinitelyOnMVar', 'BlockedIndefinitelyOnSTM', and
178 'ThreadKilled', and passes all other exceptions to the uncaught
179 exception handler (see 'setUncaughtExceptionHandler').
180 -}
181 forkIO :: IO () -> IO ThreadId
182 forkIO action = IO $ \ s ->
183    case (fork# action_plus s) of (# s1, tid #) -> (# s1, ThreadId tid #)
184  where
185   action_plus = catchException action childHandler
186
187 -- | Like 'forkIO', but the child thread is created with asynchronous exceptions
188 -- unmasked (see 'Control.Exception.mask').
189 forkIOUnmasked :: IO () -> IO ThreadId
190 forkIOUnmasked io = forkIO (unsafeUnmask io)
191
192 {- |
193 Like 'forkIO', but lets you specify on which CPU the thread is
194 created.  Unlike a `forkIO` thread, a thread created by `forkOnIO`
195 will stay on the same CPU for its entire lifetime (`forkIO` threads
196 can migrate between CPUs according to the scheduling policy).
197 `forkOnIO` is useful for overriding the scheduling policy when you
198 know in advance how best to distribute the threads.
199
200 The `Int` argument specifies the CPU number; it is interpreted modulo
201 'numCapabilities' (note that it actually specifies a capability number
202 rather than a CPU number, but to a first approximation the two are
203 equivalent).
204 -}
205 forkOnIO :: Int -> IO () -> IO ThreadId
206 forkOnIO (I# cpu) action = IO $ \ s ->
207    case (forkOn# cpu action_plus s) of (# s1, tid #) -> (# s1, ThreadId tid #)
208  where
209   action_plus = catchException action childHandler
210
211 -- | Like 'forkOnIO', but the child thread is created with
212 -- asynchronous exceptions unmasked (see 'Control.Exception.mask').
213 forkOnIOUnmasked :: Int -> IO () -> IO ThreadId
214 forkOnIOUnmasked cpu io = forkOnIO cpu (unsafeUnmask io)
215
216 -- | the value passed to the @+RTS -N@ flag.  This is the number of
217 -- Haskell threads that can run truly simultaneously at any given
218 -- time, and is typically set to the number of physical CPU cores on
219 -- the machine.
220 numCapabilities :: Int
221 numCapabilities = unsafePerformIO $  do
222                     n <- peek n_capabilities
223                     return (fromIntegral n)
224
225 -- | Returns the number of sparks currently in the local spark pool
226 numSparks :: IO Int
227 numSparks = IO $ \s -> case numSparks# s of (# s', n #) -> (# s', I# n #)
228
229 #if defined(mingw32_HOST_OS) && defined(__PIC__)
230 foreign import ccall "_imp__n_capabilities" n_capabilities :: Ptr CInt
231 #else
232 foreign import ccall "&n_capabilities" n_capabilities :: Ptr CInt
233 #endif
234 childHandler :: SomeException -> IO ()
235 childHandler err = catchException (real_handler err) childHandler
236
237 real_handler :: SomeException -> IO ()
238 real_handler se@(SomeException ex) =
239   -- ignore thread GC and killThread exceptions:
240   case cast ex of
241   Just BlockedIndefinitelyOnMVar        -> return ()
242   _ -> case cast ex of
243        Just BlockedIndefinitelyOnSTM    -> return ()
244        _ -> case cast ex of
245             Just ThreadKilled           -> return ()
246             _ -> case cast ex of
247                  -- report all others:
248                  Just StackOverflow     -> reportStackOverflow
249                  _                      -> reportError se
250
251 {- | 'killThread' raises the 'ThreadKilled' exception in the given
252 thread (GHC only).
253
254 > killThread tid = throwTo tid ThreadKilled
255
256 -}
257 killThread :: ThreadId -> IO ()
258 killThread tid = throwTo tid ThreadKilled
259
260 {- | 'throwTo' raises an arbitrary exception in the target thread (GHC only).
261
262 'throwTo' does not return until the exception has been raised in the
263 target thread.
264 The calling thread can thus be certain that the target
265 thread has received the exception.  This is a useful property to know
266 when dealing with race conditions: eg. if there are two threads that
267 can kill each other, it is guaranteed that only one of the threads
268 will get to kill the other.
269
270 Whatever work the target thread was doing when the exception was
271 raised is not lost: the computation is suspended until required by
272 another thread.
273
274 If the target thread is currently making a foreign call, then the
275 exception will not be raised (and hence 'throwTo' will not return)
276 until the call has completed.  This is the case regardless of whether
277 the call is inside a 'mask' or not.
278
279 Important note: the behaviour of 'throwTo' differs from that described in
280 the paper \"Asynchronous exceptions in Haskell\"
281 (<http://research.microsoft.com/~simonpj/Papers/asynch-exns.htm>).
282 In the paper, 'throwTo' is non-blocking; but the library implementation adopts
283 a more synchronous design in which 'throwTo' does not return until the exception
284 is received by the target thread.  The trade-off is discussed in Section 9 of the paper.
285 Like any blocking operation, 'throwTo' is therefore interruptible (see Section 5.3 of
286 the paper).  Unlike other interruptible operations, however, 'throwTo'
287 is /always/ interruptible, even if it does not actually block.
288
289 There is no guarantee that the exception will be delivered promptly,
290 although the runtime will endeavour to ensure that arbitrary
291 delays don't occur.  In GHC, an exception can only be raised when a
292 thread reaches a /safe point/, where a safe point is where memory
293 allocation occurs.  Some loops do not perform any memory allocation
294 inside the loop and therefore cannot be interrupted by a 'throwTo'.
295
296 Blocked 'throwTo' is fair: if multiple threads are trying to throw an
297 exception to the same target thread, they will succeed in FIFO order.
298
299   -}
300 throwTo :: Exception e => ThreadId -> e -> IO ()
301 throwTo (ThreadId tid) ex = IO $ \ s ->
302    case (killThread# tid (toException ex) s) of s1 -> (# s1, () #)
303
304 -- | Returns the 'ThreadId' of the calling thread (GHC only).
305 myThreadId :: IO ThreadId
306 myThreadId = IO $ \s ->
307    case (myThreadId# s) of (# s1, tid #) -> (# s1, ThreadId tid #)
308
309
310 -- |The 'yield' action allows (forces, in a co-operative multitasking
311 -- implementation) a context-switch to any other currently runnable
312 -- threads (if any), and is occasionally useful when implementing
313 -- concurrency abstractions.
314 yield :: IO ()
315 yield = IO $ \s ->
316    case (yield# s) of s1 -> (# s1, () #)
317
318 {- | 'labelThread' stores a string as identifier for this thread if
319 you built a RTS with debugging support. This identifier will be used in
320 the debugging output to make distinction of different threads easier
321 (otherwise you only have the thread state object\'s address in the heap).
322
323 Other applications like the graphical Concurrent Haskell Debugger
324 (<http://www.informatik.uni-kiel.de/~fhu/chd/>) may choose to overload
325 'labelThread' for their purposes as well.
326 -}
327
328 labelThread :: ThreadId -> String -> IO ()
329 labelThread (ThreadId t) str = IO $ \ s ->
330    let !ps  = packCString# str
331        !adr = byteArrayContents# ps in
332      case (labelThread# t adr s) of s1 -> (# s1, () #)
333
334 --      Nota Bene: 'pseq' used to be 'seq'
335 --                 but 'seq' is now defined in PrelGHC
336 --
337 -- "pseq" is defined a bit weirdly (see below)
338 --
339 -- The reason for the strange "lazy" call is that
340 -- it fools the compiler into thinking that pseq  and par are non-strict in
341 -- their second argument (even if it inlines pseq at the call site).
342 -- If it thinks pseq is strict in "y", then it often evaluates
343 -- "y" before "x", which is totally wrong.
344
345 {-# INLINE pseq  #-}
346 pseq :: a -> b -> b
347 pseq  x y = x `seq` lazy y
348
349 {-# INLINE par  #-}
350 par :: a -> b -> b
351 par  x y = case (par# x) of { _ -> lazy y }
352
353 -- | Internal function used by the RTS to run sparks.
354 runSparks :: IO ()
355 runSparks = IO loop
356   where loop s = case getSpark# s of
357                    (# s', n, p #) ->
358                       if n ==# 0# then (# s', () #)
359                                   else p `seq` loop s'
360
361 data BlockReason
362   = BlockedOnMVar
363         -- ^blocked on on 'MVar'
364   | BlockedOnBlackHole
365         -- ^blocked on a computation in progress by another thread
366   | BlockedOnException
367         -- ^blocked in 'throwTo'
368   | BlockedOnSTM
369         -- ^blocked in 'retry' in an STM transaction
370   | BlockedOnForeignCall
371         -- ^currently in a foreign call
372   | BlockedOnOther
373         -- ^blocked on some other resource.  Without @-threaded@,
374         -- I\/O and 'threadDelay' show up as 'BlockedOnOther', with @-threaded@
375         -- they show up as 'BlockedOnMVar'.
376   deriving (Eq,Ord,Show)
377
378 -- | The current status of a thread
379 data ThreadStatus
380   = ThreadRunning
381         -- ^the thread is currently runnable or running
382   | ThreadFinished
383         -- ^the thread has finished
384   | ThreadBlocked  BlockReason
385         -- ^the thread is blocked on some resource
386   | ThreadDied
387         -- ^the thread received an uncaught exception
388   deriving (Eq,Ord,Show)
389
390 threadStatus :: ThreadId -> IO ThreadStatus
391 threadStatus (ThreadId t) = IO $ \s ->
392    case threadStatus# t s of
393      (# s', stat #) -> (# s', mk_stat (I# stat) #)
394    where
395         -- NB. keep these in sync with includes/Constants.h
396      mk_stat 0  = ThreadRunning
397      mk_stat 1  = ThreadBlocked BlockedOnMVar
398      mk_stat 2  = ThreadBlocked BlockedOnBlackHole
399      mk_stat 3  = ThreadBlocked BlockedOnException
400      mk_stat 7  = ThreadBlocked BlockedOnSTM
401      mk_stat 11 = ThreadBlocked BlockedOnForeignCall
402      mk_stat 12 = ThreadBlocked BlockedOnForeignCall
403      mk_stat 16 = ThreadFinished
404      mk_stat 17 = ThreadDied
405      mk_stat _  = ThreadBlocked BlockedOnOther
406 \end{code}
407
408
409 %************************************************************************
410 %*                                                                      *
411 \subsection[stm]{Transactional heap operations}
412 %*                                                                      *
413 %************************************************************************
414
415 TVars are shared memory locations which support atomic memory
416 transactions.
417
418 \begin{code}
419 -- |A monad supporting atomic memory transactions.
420 newtype STM a = STM (State# RealWorld -> (# State# RealWorld, a #))
421
422 unSTM :: STM a -> (State# RealWorld -> (# State# RealWorld, a #))
423 unSTM (STM a) = a
424
425 INSTANCE_TYPEABLE1(STM,stmTc,"STM")
426
427 instance  Functor STM where
428    fmap f x = x >>= (return . f)
429
430 instance  Monad STM  where
431     {-# INLINE return #-}
432     {-# INLINE (>>)   #-}
433     {-# INLINE (>>=)  #-}
434     m >> k      = thenSTM m k
435     return x    = returnSTM x
436     m >>= k     = bindSTM m k
437
438 bindSTM :: STM a -> (a -> STM b) -> STM b
439 bindSTM (STM m) k = STM ( \s ->
440   case m s of
441     (# new_s, a #) -> unSTM (k a) new_s
442   )
443
444 thenSTM :: STM a -> STM b -> STM b
445 thenSTM (STM m) k = STM ( \s ->
446   case m s of
447     (# new_s, _ #) -> unSTM k new_s
448   )
449
450 returnSTM :: a -> STM a
451 returnSTM x = STM (\s -> (# s, x #))
452
453 instance MonadPlus STM where
454   mzero = retry
455   mplus = orElse
456
457 -- | Unsafely performs IO in the STM monad.  Beware: this is a highly
458 -- dangerous thing to do.
459 --
460 --   * The STM implementation will often run transactions multiple
461 --     times, so you need to be prepared for this if your IO has any
462 --     side effects.
463 --
464 --   * The STM implementation will abort transactions that are known to
465 --     be invalid and need to be restarted.  This may happen in the middle
466 --     of `unsafeIOToSTM`, so make sure you don't acquire any resources
467 --     that need releasing (exception handlers are ignored when aborting
468 --     the transaction).  That includes doing any IO using Handles, for
469 --     example.  Getting this wrong will probably lead to random deadlocks.
470 --
471 --   * The transaction may have seen an inconsistent view of memory when
472 --     the IO runs.  Invariants that you expect to be true throughout
473 --     your program may not be true inside a transaction, due to the
474 --     way transactions are implemented.  Normally this wouldn't be visible
475 --     to the programmer, but using `unsafeIOToSTM` can expose it.
476 --
477 unsafeIOToSTM :: IO a -> STM a
478 unsafeIOToSTM (IO m) = STM m
479
480 -- |Perform a series of STM actions atomically.
481 --
482 -- You cannot use 'atomically' inside an 'unsafePerformIO' or 'unsafeInterleaveIO'.
483 -- Any attempt to do so will result in a runtime error.  (Reason: allowing
484 -- this would effectively allow a transaction inside a transaction, depending
485 -- on exactly when the thunk is evaluated.)
486 --
487 -- However, see 'newTVarIO', which can be called inside 'unsafePerformIO',
488 -- and which allows top-level TVars to be allocated.
489
490 atomically :: STM a -> IO a
491 atomically (STM m) = IO (\s -> (atomically# m) s )
492
493 -- |Retry execution of the current memory transaction because it has seen
494 -- values in TVars which mean that it should not continue (e.g. the TVars
495 -- represent a shared buffer that is now empty).  The implementation may
496 -- block the thread until one of the TVars that it has read from has been
497 -- udpated. (GHC only)
498 retry :: STM a
499 retry = STM $ \s# -> retry# s#
500
501 -- |Compose two alternative STM actions (GHC only).  If the first action
502 -- completes without retrying then it forms the result of the orElse.
503 -- Otherwise, if the first action retries, then the second action is
504 -- tried in its place.  If both actions retry then the orElse as a
505 -- whole retries.
506 orElse :: STM a -> STM a -> STM a
507 orElse (STM m) e = STM $ \s -> catchRetry# m (unSTM e) s
508
509 -- |Exception handling within STM actions.
510 catchSTM :: STM a -> (SomeException -> STM a) -> STM a
511 catchSTM (STM m) k = STM $ \s -> catchSTM# m (\ex -> unSTM (k ex)) s
512
513 -- | Low-level primitive on which always and alwaysSucceeds are built.
514 -- checkInv differs form these in that (i) the invariant is not
515 -- checked when checkInv is called, only at the end of this and
516 -- subsequent transcations, (ii) the invariant failure is indicated
517 -- by raising an exception.
518 checkInv :: STM a -> STM ()
519 checkInv (STM m) = STM (\s -> (check# m) s)
520
521 -- | alwaysSucceeds adds a new invariant that must be true when passed
522 -- to alwaysSucceeds, at the end of the current transaction, and at
523 -- the end of every subsequent transaction.  If it fails at any
524 -- of those points then the transaction violating it is aborted
525 -- and the exception raised by the invariant is propagated.
526 alwaysSucceeds :: STM a -> STM ()
527 alwaysSucceeds i = do ( i >> retry ) `orElse` ( return () )
528                       checkInv i
529
530 -- | always is a variant of alwaysSucceeds in which the invariant is
531 -- expressed as an STM Bool action that must return True.  Returning
532 -- False or raising an exception are both treated as invariant failures.
533 always :: STM Bool -> STM ()
534 always i = alwaysSucceeds ( do v <- i
535                                if (v) then return () else ( error "Transacional invariant violation" ) )
536
537 -- |Shared memory locations that support atomic memory transactions.
538 data TVar a = TVar (TVar# RealWorld a)
539
540 INSTANCE_TYPEABLE1(TVar,tvarTc,"TVar")
541
542 instance Eq (TVar a) where
543         (TVar tvar1#) == (TVar tvar2#) = sameTVar# tvar1# tvar2#
544
545 -- |Create a new TVar holding a value supplied
546 newTVar :: a -> STM (TVar a)
547 newTVar val = STM $ \s1# ->
548     case newTVar# val s1# of
549          (# s2#, tvar# #) -> (# s2#, TVar tvar# #)
550
551 -- |@IO@ version of 'newTVar'.  This is useful for creating top-level
552 -- 'TVar's using 'System.IO.Unsafe.unsafePerformIO', because using
553 -- 'atomically' inside 'System.IO.Unsafe.unsafePerformIO' isn't
554 -- possible.
555 newTVarIO :: a -> IO (TVar a)
556 newTVarIO val = IO $ \s1# ->
557     case newTVar# val s1# of
558          (# s2#, tvar# #) -> (# s2#, TVar tvar# #)
559
560 -- |Return the current value stored in a TVar.
561 -- This is equivalent to
562 --
563 -- >  readTVarIO = atomically . readTVar
564 --
565 -- but works much faster, because it doesn't perform a complete
566 -- transaction, it just reads the current value of the 'TVar'.
567 readTVarIO :: TVar a -> IO a
568 readTVarIO (TVar tvar#) = IO $ \s# -> readTVarIO# tvar# s#
569
570 -- |Return the current value stored in a TVar
571 readTVar :: TVar a -> STM a
572 readTVar (TVar tvar#) = STM $ \s# -> readTVar# tvar# s#
573
574 -- |Write the supplied value into a TVar
575 writeTVar :: TVar a -> a -> STM ()
576 writeTVar (TVar tvar#) val = STM $ \s1# ->
577     case writeTVar# tvar# val s1# of
578          s2# -> (# s2#, () #)
579
580 \end{code}
581
582 MVar utilities
583
584 \begin{code}
585 withMVar :: MVar a -> (a -> IO b) -> IO b
586 withMVar m io =
587   mask $ \restore -> do
588     a <- takeMVar m
589     b <- catchAny (restore (io a))
590             (\e -> do putMVar m a; throw e)
591     putMVar m a
592     return b
593
594 modifyMVar_ :: MVar a -> (a -> IO a) -> IO ()
595 modifyMVar_ m io =
596   mask $ \restore -> do
597     a <- takeMVar m
598     a' <- catchAny (restore (io a))
599             (\e -> do putMVar m a; throw e)
600     putMVar m a'
601     return ()
602 \end{code}
603
604 %************************************************************************
605 %*                                                                      *
606 \subsection{Thread waiting}
607 %*                                                                      *
608 %************************************************************************
609
610 \begin{code}
611
612 -- Machinery needed to ensureb that we only have one copy of certain
613 -- CAFs in this module even when the base package is present twice, as
614 -- it is when base is dynamically loaded into GHCi.  The RTS keeps
615 -- track of the single true value of the CAF, so even when the CAFs in
616 -- the dynamically-loaded base package are reverted, nothing bad
617 -- happens.
618 --
619 sharedCAF :: a -> (Ptr a -> IO (Ptr a)) -> IO a
620 sharedCAF a get_or_set =
621    mask_ $ do
622      stable_ref <- newStablePtr a
623      let ref = castPtr (castStablePtrToPtr stable_ref)
624      ref2 <- get_or_set ref
625      if ref==ref2
626         then return a
627         else do freeStablePtr stable_ref
628                 deRefStablePtr (castPtrToStablePtr (castPtr ref2))
629
630 reportStackOverflow :: IO ()
631 reportStackOverflow = callStackOverflowHook
632
633 reportError :: SomeException -> IO ()
634 reportError ex = do
635    handler <- getUncaughtExceptionHandler
636    handler ex
637
638 -- SUP: Are the hooks allowed to re-enter Haskell land?  If so, remove
639 -- the unsafe below.
640 foreign import ccall unsafe "stackOverflow"
641         callStackOverflowHook :: IO ()
642
643 {-# NOINLINE uncaughtExceptionHandler #-}
644 uncaughtExceptionHandler :: IORef (SomeException -> IO ())
645 uncaughtExceptionHandler = unsafePerformIO (newIORef defaultHandler)
646    where
647       defaultHandler :: SomeException -> IO ()
648       defaultHandler se@(SomeException ex) = do
649          (hFlush stdout) `catchAny` (\ _ -> return ())
650          let msg = case cast ex of
651                Just Deadlock -> "no threads to run:  infinite loop or deadlock?"
652                _ -> case cast ex of
653                     Just (ErrorCall s) -> s
654                     _                  -> showsPrec 0 se ""
655          withCString "%s" $ \cfmt ->
656           withCString msg $ \cmsg ->
657             errorBelch cfmt cmsg
658
659 -- don't use errorBelch() directly, because we cannot call varargs functions
660 -- using the FFI.
661 foreign import ccall unsafe "HsBase.h errorBelch2"
662    errorBelch :: CString -> CString -> IO ()
663
664 setUncaughtExceptionHandler :: (SomeException -> IO ()) -> IO ()
665 setUncaughtExceptionHandler = writeIORef uncaughtExceptionHandler
666
667 getUncaughtExceptionHandler :: IO (SomeException -> IO ())
668 getUncaughtExceptionHandler = readIORef uncaughtExceptionHandler
669
670 \end{code}