2 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
3 {-# OPTIONS_GHC -fno-warn-missing-signatures #-}
4 {-# OPTIONS_HADDOCK not-home #-}
5 -----------------------------------------------------------------------------
7 -- Module : GHC.Conc.Sync
8 -- Copyright : (c) The University of Glasgow, 1994-2002
9 -- License : see libraries/base/LICENSE
11 -- Maintainer : cvs-ghc@haskell.org
12 -- Stability : internal
13 -- Portability : non-portable (GHC extensions)
15 -- Basic concurrency stuff.
17 -----------------------------------------------------------------------------
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:
30 -- * Forking and suchlike
31 , forkIO -- :: IO a -> IO ThreadId
33 , forkOnIO -- :: Int -> IO a -> IO ThreadId
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
45 , labelThread -- :: ThreadId -> String -> IO ()
47 , ThreadStatus(..), BlockReason(..)
48 , threadStatus -- :: ThreadId -> IO ThreadStatus
52 , atomically -- :: STM a -> IO 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 ()
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
70 , setUncaughtExceptionHandler -- :: (Exception -> IO ()) -> IO ()
71 , getUncaughtExceptionHandler -- :: IO (Exception -> IO ())
73 , reportError, reportStackOverflow
78 import Foreign hiding (unsafePerformIO)
81 #ifdef mingw32_HOST_OS
85 #ifndef mingw32_HOST_OS
92 import {-# SOURCE #-} GHC.IO.Handle ( hFlush )
93 import {-# SOURCE #-} GHC.IO.Handle.FD ( stdout )
95 import GHC.IO.Exception
99 import GHC.Num ( Num(..) )
100 import GHC.Real ( fromIntegral )
101 import GHC.Pack ( packCString# )
102 import GHC.Show ( Show(..), showString )
104 infixr 0 `par`, `pseq`
107 %************************************************************************
109 \subsection{@ThreadId@, @par@, and @fork@}
111 %************************************************************************
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
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
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.
132 /Note/: Hugs does not provide any operations on other threads;
133 it defines 'ThreadId' as a synonym for ().
136 instance Show ThreadId where
138 showString "ThreadId " .
139 showsPrec d (getThreadId (id2TSO t))
141 foreign import ccall unsafe "rts_getThreadId" getThreadId :: ThreadId# -> CInt
143 id2TSO :: ThreadId -> ThreadId#
144 id2TSO (ThreadId t) = t
146 foreign import ccall unsafe "cmp_thread" cmp_thread :: ThreadId# -> ThreadId# -> CInt
149 cmpThread :: ThreadId -> ThreadId -> Ordering
151 case cmp_thread (id2TSO t1) (id2TSO t2) of
156 instance Eq ThreadId where
158 case t1 `cmpThread` t2 of
162 instance Ord ThreadId where
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
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.
173 GHC note: the new thread inherits the /masked/ state of the parent
174 (see 'Control.Exception.mask').
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').
181 forkIO :: IO () -> IO ThreadId
182 forkIO action = IO $ \ s ->
183 case (fork# action_plus s) of (# s1, tid #) -> (# s1, ThreadId tid #)
185 action_plus = catchException action childHandler
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)
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.
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
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 #)
209 action_plus = catchException action childHandler
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)
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
220 numCapabilities :: Int
221 numCapabilities = unsafePerformIO $ do
222 n <- peek n_capabilities
223 return (fromIntegral n)
225 -- | Returns the number of sparks currently in the local spark pool
227 numSparks = IO $ \s -> case numSparks# s of (# s', n #) -> (# s', I# n #)
229 #if defined(mingw32_HOST_OS) && defined(__PIC__)
230 foreign import ccall "_imp__n_capabilities" n_capabilities :: Ptr CInt
232 foreign import ccall "&n_capabilities" n_capabilities :: Ptr CInt
234 childHandler :: SomeException -> IO ()
235 childHandler err = catchException (real_handler err) childHandler
237 real_handler :: SomeException -> IO ()
238 real_handler se@(SomeException ex) =
239 -- ignore thread GC and killThread exceptions:
241 Just BlockedIndefinitelyOnMVar -> return ()
243 Just BlockedIndefinitelyOnSTM -> return ()
245 Just ThreadKilled -> return ()
247 -- report all others:
248 Just StackOverflow -> reportStackOverflow
251 {- | 'killThread' raises the 'ThreadKilled' exception in the given
254 > killThread tid = throwTo tid ThreadKilled
257 killThread :: ThreadId -> IO ()
258 killThread tid = throwTo tid ThreadKilled
260 {- | 'throwTo' raises an arbitrary exception in the target thread (GHC only).
262 'throwTo' does not return until the exception has been raised in the
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.
270 Whatever work the target thread was doing when the exception was
271 raised is not lost: the computation is suspended until required by
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.
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.
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'.
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.
300 throwTo :: Exception e => ThreadId -> e -> IO ()
301 throwTo (ThreadId tid) ex = IO $ \ s ->
302 case (killThread# tid (toException ex) s) of s1 -> (# s1, () #)
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 #)
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.
316 case (yield# s) of s1 -> (# s1, () #)
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).
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.
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, () #)
334 -- Nota Bene: 'pseq' used to be 'seq'
335 -- but 'seq' is now defined in PrelGHC
337 -- "pseq" is defined a bit weirdly (see below)
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.
347 pseq x y = x `seq` lazy y
351 par x y = case (par# x) of { _ -> lazy y }
353 -- | Internal function used by the RTS to run sparks.
356 where loop s = case getSpark# s of
358 if n ==# 0# then (# s', () #)
363 -- ^blocked on on 'MVar'
365 -- ^blocked on a computation in progress by another thread
367 -- ^blocked in 'throwTo'
369 -- ^blocked in 'retry' in an STM transaction
370 | BlockedOnForeignCall
371 -- ^currently in a foreign call
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)
378 -- | The current status of a thread
381 -- ^the thread is currently runnable or running
383 -- ^the thread has finished
384 | ThreadBlocked BlockReason
385 -- ^the thread is blocked on some resource
387 -- ^the thread received an uncaught exception
388 deriving (Eq,Ord,Show)
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) #)
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
409 %************************************************************************
411 \subsection[stm]{Transactional heap operations}
413 %************************************************************************
415 TVars are shared memory locations which support atomic memory
419 -- |A monad supporting atomic memory transactions.
420 newtype STM a = STM (State# RealWorld -> (# State# RealWorld, a #))
422 unSTM :: STM a -> (State# RealWorld -> (# State# RealWorld, a #))
425 INSTANCE_TYPEABLE1(STM,stmTc,"STM")
427 instance Functor STM where
428 fmap f x = x >>= (return . f)
430 instance Monad STM where
431 {-# INLINE return #-}
435 return x = returnSTM x
436 m >>= k = bindSTM m k
438 bindSTM :: STM a -> (a -> STM b) -> STM b
439 bindSTM (STM m) k = STM ( \s ->
441 (# new_s, a #) -> unSTM (k a) new_s
444 thenSTM :: STM a -> STM b -> STM b
445 thenSTM (STM m) k = STM ( \s ->
447 (# new_s, _ #) -> unSTM k new_s
450 returnSTM :: a -> STM a
451 returnSTM x = STM (\s -> (# s, x #))
453 instance MonadPlus STM where
457 -- | Unsafely performs IO in the STM monad. Beware: this is a highly
458 -- dangerous thing to do.
460 -- * The STM implementation will often run transactions multiple
461 -- times, so you need to be prepared for this if your IO has any
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.
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.
477 unsafeIOToSTM :: IO a -> STM a
478 unsafeIOToSTM (IO m) = STM m
480 -- |Perform a series of STM actions atomically.
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.)
487 -- However, see 'newTVarIO', which can be called inside 'unsafePerformIO',
488 -- and which allows top-level TVars to be allocated.
490 atomically :: STM a -> IO a
491 atomically (STM m) = IO (\s -> (atomically# m) s )
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)
499 retry = STM $ \s# -> retry# s#
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
506 orElse :: STM a -> STM a -> STM a
507 orElse (STM m) e = STM $ \s -> catchRetry# m (unSTM e) s
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
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)
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 () )
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" ) )
537 -- |Shared memory locations that support atomic memory transactions.
538 data TVar a = TVar (TVar# RealWorld a)
540 INSTANCE_TYPEABLE1(TVar,tvarTc,"TVar")
542 instance Eq (TVar a) where
543 (TVar tvar1#) == (TVar tvar2#) = sameTVar# tvar1# tvar2#
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# #)
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
555 newTVarIO :: a -> IO (TVar a)
556 newTVarIO val = IO $ \s1# ->
557 case newTVar# val s1# of
558 (# s2#, tvar# #) -> (# s2#, TVar tvar# #)
560 -- |Return the current value stored in a TVar.
561 -- This is equivalent to
563 -- > readTVarIO = atomically . readTVar
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#
570 -- |Return the current value stored in a TVar
571 readTVar :: TVar a -> STM a
572 readTVar (TVar tvar#) = STM $ \s# -> readTVar# tvar# s#
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
585 withMVar :: MVar a -> (a -> IO b) -> IO b
587 mask $ \restore -> do
589 b <- catchAny (restore (io a))
590 (\e -> do putMVar m a; throw e)
594 modifyMVar_ :: MVar a -> (a -> IO a) -> IO ()
596 mask $ \restore -> do
598 a' <- catchAny (restore (io a))
599 (\e -> do putMVar m a; throw e)
604 %************************************************************************
606 \subsection{Thread waiting}
608 %************************************************************************
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
619 sharedCAF :: a -> (Ptr a -> IO (Ptr a)) -> IO a
620 sharedCAF a get_or_set =
622 stable_ref <- newStablePtr a
623 let ref = castPtr (castStablePtrToPtr stable_ref)
624 ref2 <- get_or_set ref
627 else do freeStablePtr stable_ref
628 deRefStablePtr (castPtrToStablePtr (castPtr ref2))
630 reportStackOverflow :: IO ()
631 reportStackOverflow = callStackOverflowHook
633 reportError :: SomeException -> IO ()
635 handler <- getUncaughtExceptionHandler
638 -- SUP: Are the hooks allowed to re-enter Haskell land? If so, remove
640 foreign import ccall unsafe "stackOverflow"
641 callStackOverflowHook :: IO ()
643 {-# NOINLINE uncaughtExceptionHandler #-}
644 uncaughtExceptionHandler :: IORef (SomeException -> IO ())
645 uncaughtExceptionHandler = unsafePerformIO (newIORef defaultHandler)
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?"
653 Just (ErrorCall s) -> s
654 _ -> showsPrec 0 se ""
655 withCString "%s" $ \cfmt ->
656 withCString msg $ \cmsg ->
659 -- don't use errorBelch() directly, because we cannot call varargs functions
661 foreign import ccall unsafe "HsBase.h errorBelch2"
662 errorBelch :: CString -> CString -> IO ()
664 setUncaughtExceptionHandler :: (SomeException -> IO ()) -> IO ()
665 setUncaughtExceptionHandler = writeIORef uncaughtExceptionHandler
667 getUncaughtExceptionHandler :: IO (SomeException -> IO ())
668 getUncaughtExceptionHandler = readIORef uncaughtExceptionHandler