2 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
3 {-# OPTIONS_HADDOCK not-home #-}
4 -----------------------------------------------------------------------------
7 -- Copyright : (c) The University of Glasgow, 1994-2002
8 -- License : see libraries/base/LICENSE
10 -- Maintainer : cvs-ghc@haskell.org
11 -- Stability : internal
12 -- Portability : non-portable (GHC extensions)
14 -- Basic concurrency stuff.
16 -----------------------------------------------------------------------------
18 -- No: #hide, because bits of this module are exposed by the stm package.
19 -- However, we don't want this module to be the home location for the
20 -- bits it exports, we'd rather have Control.Concurrent and the other
21 -- higher level modules be the home. Hence:
29 -- * Forking and suchlike
30 , forkIO -- :: IO a -> IO ThreadId
31 , forkOnIO -- :: Int -> IO a -> IO ThreadId
32 , numCapabilities -- :: Int
33 , childHandler -- :: Exception -> IO ()
34 , myThreadId -- :: IO ThreadId
35 , killThread -- :: ThreadId -> IO ()
36 , throwTo -- :: ThreadId -> Exception -> IO ()
37 , par -- :: a -> b -> b
38 , pseq -- :: a -> b -> b
40 , labelThread -- :: ThreadId -> String -> IO ()
42 , ThreadStatus(..), BlockReason(..)
43 , threadStatus -- :: ThreadId -> IO ThreadStatus
46 , threadDelay -- :: Int -> IO ()
47 , registerDelay -- :: Int -> IO (TVar Bool)
48 , threadWaitRead -- :: Int -> IO ()
49 , threadWaitWrite -- :: Int -> IO ()
53 , newMVar -- :: a -> IO (MVar a)
54 , newEmptyMVar -- :: IO (MVar a)
55 , takeMVar -- :: MVar a -> IO a
56 , putMVar -- :: MVar a -> a -> IO ()
57 , tryTakeMVar -- :: MVar a -> IO (Maybe a)
58 , tryPutMVar -- :: MVar a -> a -> IO Bool
59 , isEmptyMVar -- :: MVar a -> IO Bool
60 , addMVarFinalizer -- :: MVar a -> IO () -> IO ()
64 , atomically -- :: STM a -> IO a
66 , orElse -- :: STM a -> STM a -> STM a
67 , catchSTM -- :: STM a -> (Exception -> STM a) -> STM a
68 , alwaysSucceeds -- :: STM a -> STM ()
69 , always -- :: STM Bool -> STM ()
71 , newTVar -- :: a -> STM (TVar a)
72 , newTVarIO -- :: a -> STM (TVar a)
73 , readTVar -- :: TVar a -> STM a
74 , writeTVar -- :: a -> TVar a -> STM ()
75 , unsafeIOToSTM -- :: IO a -> STM a
78 #ifdef mingw32_HOST_OS
79 , asyncRead -- :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
80 , asyncWrite -- :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
81 , asyncDoProc -- :: FunPtr (Ptr a -> IO Int) -> Ptr a -> IO Int
83 , asyncReadBA -- :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int, Int)
84 , asyncWriteBA -- :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int, Int)
87 #ifndef mingw32_HOST_OS
91 , ensureIOManagerIsRunning
93 #ifdef mingw32_HOST_OS
98 , setUncaughtExceptionHandler -- :: (Exception -> IO ()) -> IO ()
99 , getUncaughtExceptionHandler -- :: IO (Exception -> IO ())
101 , reportError, reportStackOverflow
104 import System.Posix.Types
105 #ifndef mingw32_HOST_OS
106 import System.Posix.Internals
114 import {-# SOURCE #-} GHC.Handle
116 import GHC.Num ( Num(..) )
117 import GHC.Real ( fromIntegral, div )
118 #ifndef mingw32_HOST_OS
119 import GHC.Base ( Int(..) )
121 #ifdef mingw32_HOST_OS
122 import GHC.Read ( Read )
123 import GHC.Enum ( Enum )
125 import GHC.Exception ( SomeException(..), throw )
126 import GHC.Pack ( packCString# )
127 import GHC.Ptr ( Ptr(..), plusPtr, FunPtr(..) )
129 import GHC.Show ( Show(..), showString )
133 infixr 0 `par`, `pseq`
136 %************************************************************************
138 \subsection{@ThreadId@, @par@, and @fork@}
140 %************************************************************************
143 data ThreadId = ThreadId ThreadId# deriving( Typeable )
144 -- ToDo: data ThreadId = ThreadId (Weak ThreadId#)
145 -- But since ThreadId# is unlifted, the Weak type must use open
148 A 'ThreadId' is an abstract type representing a handle to a thread.
149 'ThreadId' is an instance of 'Eq', 'Ord' and 'Show', where
150 the 'Ord' instance implements an arbitrary total ordering over
151 'ThreadId's. The 'Show' instance lets you convert an arbitrary-valued
152 'ThreadId' to string form; showing a 'ThreadId' value is occasionally
153 useful when debugging or diagnosing the behaviour of a concurrent
156 /Note/: in GHC, if you have a 'ThreadId', you essentially have
157 a pointer to the thread itself. This means the thread itself can\'t be
158 garbage collected until you drop the 'ThreadId'.
159 This misfeature will hopefully be corrected at a later date.
161 /Note/: Hugs does not provide any operations on other threads;
162 it defines 'ThreadId' as a synonym for ().
165 instance Show ThreadId where
167 showString "ThreadId " .
168 showsPrec d (getThreadId (id2TSO t))
170 foreign import ccall unsafe "rts_getThreadId" getThreadId :: ThreadId# -> CInt
172 id2TSO :: ThreadId -> ThreadId#
173 id2TSO (ThreadId t) = t
175 foreign import ccall unsafe "cmp_thread" cmp_thread :: ThreadId# -> ThreadId# -> CInt
178 cmpThread :: ThreadId -> ThreadId -> Ordering
180 case cmp_thread (id2TSO t1) (id2TSO t2) of
185 instance Eq ThreadId where
187 case t1 `cmpThread` t2 of
191 instance Ord ThreadId where
195 Sparks off a new thread to run the 'IO' computation passed as the
196 first argument, and returns the 'ThreadId' of the newly created
199 The new thread will be a lightweight thread; if you want to use a foreign
200 library that uses thread-local storage, use 'Control.Concurrent.forkOS' instead.
202 GHC note: the new thread inherits the /blocked/ state of the parent
203 (see 'Control.Exception.block').
205 forkIO :: IO () -> IO ThreadId
206 forkIO action = IO $ \ s ->
207 case (fork# action_plus s) of (# s1, id #) -> (# s1, ThreadId id #)
209 action_plus = catchException action childHandler
212 Like 'forkIO', but lets you specify on which CPU the thread is
213 created. Unlike a `forkIO` thread, a thread created by `forkOnIO`
214 will stay on the same CPU for its entire lifetime (`forkIO` threads
215 can migrate between CPUs according to the scheduling policy).
216 `forkOnIO` is useful for overriding the scheduling policy when you
217 know in advance how best to distribute the threads.
219 The `Int` argument specifies the CPU number; it is interpreted modulo
220 'numCapabilities' (note that it actually specifies a capability number
221 rather than a CPU number, but to a first approximation the two are
224 forkOnIO :: Int -> IO () -> IO ThreadId
225 forkOnIO (I# cpu) action = IO $ \ s ->
226 case (forkOn# cpu action_plus s) of (# s1, id #) -> (# s1, ThreadId id #)
228 action_plus = catchException action childHandler
230 -- | the value passed to the @+RTS -N@ flag. This is the number of
231 -- Haskell threads that can run truly simultaneously at any given
232 -- time, and is typically set to the number of physical CPU cores on
234 numCapabilities :: Int
235 numCapabilities = unsafePerformIO $ do
236 n <- peek n_capabilities
237 return (fromIntegral n)
239 foreign import ccall "&n_capabilities" n_capabilities :: Ptr CInt
241 childHandler :: SomeException -> IO ()
242 childHandler err = catchException (real_handler err) childHandler
244 real_handler :: SomeException -> IO ()
245 real_handler se@(SomeException ex) =
246 -- ignore thread GC and killThread exceptions:
248 Just BlockedOnDeadMVar -> return ()
250 Just BlockedIndefinitely -> return ()
252 Just ThreadKilled -> return ()
254 -- report all others:
255 Just StackOverflow -> reportStackOverflow
258 {- | 'killThread' terminates the given thread (GHC only).
259 Any work already done by the thread isn\'t
260 lost: the computation is suspended until required by another thread.
261 The memory used by the thread will be garbage collected if it isn\'t
262 referenced from anywhere. The 'killThread' function is defined in
265 > killThread tid = throwTo tid (AsyncException ThreadKilled)
268 killThread :: ThreadId -> IO ()
269 killThread tid = throwTo tid (toException ThreadKilled)
271 {- | 'throwTo' raises an arbitrary exception in the target thread (GHC only).
273 'throwTo' does not return until the exception has been raised in the
275 The calling thread can thus be certain that the target
276 thread has received the exception. This is a useful property to know
277 when dealing with race conditions: eg. if there are two threads that
278 can kill each other, it is guaranteed that only one of the threads
279 will get to kill the other.
281 If the target thread is currently making a foreign call, then the
282 exception will not be raised (and hence 'throwTo' will not return)
283 until the call has completed. This is the case regardless of whether
284 the call is inside a 'block' or not.
286 Important note: the behaviour of 'throwTo' differs from that described in
287 the paper \"Asynchronous exceptions in Haskell\"
288 (<http://research.microsoft.com/~simonpj/Papers/asynch-exns.htm>).
289 In the paper, 'throwTo' is non-blocking; but the library implementation adopts
290 a more synchronous design in which 'throwTo' does not return until the exception
291 is received by the target thread. The trade-off is discussed in Section 8 of the paper.
292 Like any blocking operation, 'throwTo' is therefore interruptible (see Section 4.3 of
295 There is currently no guarantee that the exception delivered by 'throwTo' will be
296 delivered at the first possible opportunity. In particular, if a thread may
297 unblock and then re-block exceptions (using 'unblock' and 'block') without receiving
298 a pending 'throwTo'. This is arguably undesirable behaviour.
301 -- XXX This is duplicated in Control.{Old,}Exception
302 throwTo :: ThreadId -> SomeException -> IO ()
303 throwTo (ThreadId id) ex = IO $ \ s ->
304 case (killThread# id ex s) of s1 -> (# s1, () #)
306 -- | Returns the 'ThreadId' of the calling thread (GHC only).
307 myThreadId :: IO ThreadId
308 myThreadId = IO $ \s ->
309 case (myThreadId# s) of (# s1, id #) -> (# s1, ThreadId id #)
312 -- |The 'yield' action allows (forces, in a co-operative multitasking
313 -- implementation) a context-switch to any other currently runnable
314 -- threads (if any), and is occasionally useful when implementing
315 -- concurrency abstractions.
318 case (yield# s) of s1 -> (# s1, () #)
320 {- | 'labelThread' stores a string as identifier for this thread if
321 you built a RTS with debugging support. This identifier will be used in
322 the debugging output to make distinction of different threads easier
323 (otherwise you only have the thread state object\'s address in the heap).
325 Other applications like the graphical Concurrent Haskell Debugger
326 (<http://www.informatik.uni-kiel.de/~fhu/chd/>) may choose to overload
327 'labelThread' for their purposes as well.
330 labelThread :: ThreadId -> String -> IO ()
331 labelThread (ThreadId t) str = IO $ \ s ->
332 let ps = packCString# str
333 adr = byteArrayContents# ps in
334 case (labelThread# t adr s) of s1 -> (# s1, () #)
336 -- Nota Bene: 'pseq' used to be 'seq'
337 -- but 'seq' is now defined in PrelGHC
339 -- "pseq" is defined a bit weirdly (see below)
341 -- The reason for the strange "lazy" call is that
342 -- it fools the compiler into thinking that pseq and par are non-strict in
343 -- their second argument (even if it inlines pseq at the call site).
344 -- If it thinks pseq is strict in "y", then it often evaluates
345 -- "y" before "x", which is totally wrong.
349 pseq x y = x `seq` lazy y
353 par x y = case (par# x) of { _ -> lazy y }
358 -- ^blocked on on 'MVar'
360 -- ^blocked on a computation in progress by another thread
362 -- ^blocked in 'throwTo'
364 -- ^blocked in 'retry' in an STM transaction
365 | BlockedOnForeignCall
366 -- ^currently in a foreign call
368 -- ^blocked on some other resource. Without @-threaded@,
369 -- I\/O and 'threadDelay' show up as 'BlockedOnOther', with @-threaded@
370 -- they show up as 'BlockedOnMVar'.
371 deriving (Eq,Ord,Show)
373 -- | The current status of a thread
376 -- ^the thread is currently runnable or running
378 -- ^the thread has finished
379 | ThreadBlocked BlockReason
380 -- ^the thread is blocked on some resource
382 -- ^the thread received an uncaught exception
383 deriving (Eq,Ord,Show)
385 threadStatus :: ThreadId -> IO ThreadStatus
386 threadStatus (ThreadId t) = IO $ \s ->
387 case threadStatus# t s of
388 (# s', stat #) -> (# s', mk_stat (I# stat) #)
390 -- NB. keep these in sync with includes/Constants.h
391 mk_stat 0 = ThreadRunning
392 mk_stat 1 = ThreadBlocked BlockedOnMVar
393 mk_stat 2 = ThreadBlocked BlockedOnBlackHole
394 mk_stat 3 = ThreadBlocked BlockedOnException
395 mk_stat 7 = ThreadBlocked BlockedOnSTM
396 mk_stat 11 = ThreadBlocked BlockedOnForeignCall
397 mk_stat 12 = ThreadBlocked BlockedOnForeignCall
398 mk_stat 16 = ThreadFinished
399 mk_stat 17 = ThreadDied
400 mk_stat _ = ThreadBlocked BlockedOnOther
404 %************************************************************************
406 \subsection[stm]{Transactional heap operations}
408 %************************************************************************
410 TVars are shared memory locations which support atomic memory
414 -- |A monad supporting atomic memory transactions.
415 newtype STM a = STM (State# RealWorld -> (# State# RealWorld, a #))
417 unSTM :: STM a -> (State# RealWorld -> (# State# RealWorld, a #))
420 INSTANCE_TYPEABLE1(STM,stmTc,"STM")
422 instance Functor STM where
423 fmap f x = x >>= (return . f)
425 instance Monad STM where
426 {-# INLINE return #-}
430 return x = returnSTM x
431 m >>= k = bindSTM m k
433 bindSTM :: STM a -> (a -> STM b) -> STM b
434 bindSTM (STM m) k = STM ( \s ->
436 (# new_s, a #) -> unSTM (k a) new_s
439 thenSTM :: STM a -> STM b -> STM b
440 thenSTM (STM m) k = STM ( \s ->
442 (# new_s, a #) -> unSTM k new_s
445 returnSTM :: a -> STM a
446 returnSTM x = STM (\s -> (# s, x #))
448 -- | Unsafely performs IO in the STM monad. Beware: this is a highly
449 -- dangerous thing to do.
451 -- * The STM implementation will often run transactions multiple
452 -- times, so you need to be prepared for this if your IO has any
455 -- * The STM implementation will abort transactions that are known to
456 -- be invalid and need to be restarted. This may happen in the middle
457 -- of `unsafeIOToSTM`, so make sure you don't acquire any resources
458 -- that need releasing (exception handlers are ignored when aborting
459 -- the transaction). That includes doing any IO using Handles, for
460 -- example. Getting this wrong will probably lead to random deadlocks.
462 -- * The transaction may have seen an inconsistent view of memory when
463 -- the IO runs. Invariants that you expect to be true throughout
464 -- your program may not be true inside a transaction, due to the
465 -- way transactions are implemented. Normally this wouldn't be visible
466 -- to the programmer, but using `unsafeIOToSTM` can expose it.
468 unsafeIOToSTM :: IO a -> STM a
469 unsafeIOToSTM (IO m) = STM m
471 -- |Perform a series of STM actions atomically.
473 -- You cannot use 'atomically' inside an 'unsafePerformIO' or 'unsafeInterleaveIO'.
474 -- Any attempt to do so will result in a runtime error. (Reason: allowing
475 -- this would effectively allow a transaction inside a transaction, depending
476 -- on exactly when the thunk is evaluated.)
478 -- However, see 'newTVarIO', which can be called inside 'unsafePerformIO',
479 -- and which allows top-level TVars to be allocated.
481 atomically :: STM a -> IO a
482 atomically (STM m) = IO (\s -> (atomically# m) s )
484 -- |Retry execution of the current memory transaction because it has seen
485 -- values in TVars which mean that it should not continue (e.g. the TVars
486 -- represent a shared buffer that is now empty). The implementation may
487 -- block the thread until one of the TVars that it has read from has been
488 -- udpated. (GHC only)
490 retry = STM $ \s# -> retry# s#
492 -- |Compose two alternative STM actions (GHC only). If the first action
493 -- completes without retrying then it forms the result of the orElse.
494 -- Otherwise, if the first action retries, then the second action is
495 -- tried in its place. If both actions retry then the orElse as a
497 orElse :: STM a -> STM a -> STM a
498 orElse (STM m) e = STM $ \s -> catchRetry# m (unSTM e) s
500 -- |Exception handling within STM actions.
501 catchSTM :: STM a -> (SomeException -> STM a) -> STM a
502 catchSTM (STM m) k = STM $ \s -> catchSTM# m (\ex -> unSTM (k ex)) s
504 -- | Low-level primitive on which always and alwaysSucceeds are built.
505 -- checkInv differs form these in that (i) the invariant is not
506 -- checked when checkInv is called, only at the end of this and
507 -- subsequent transcations, (ii) the invariant failure is indicated
508 -- by raising an exception.
509 checkInv :: STM a -> STM ()
510 checkInv (STM m) = STM (\s -> (check# m) s)
512 -- | alwaysSucceeds adds a new invariant that must be true when passed
513 -- to alwaysSucceeds, at the end of the current transaction, and at
514 -- the end of every subsequent transaction. If it fails at any
515 -- of those points then the transaction violating it is aborted
516 -- and the exception raised by the invariant is propagated.
517 alwaysSucceeds :: STM a -> STM ()
518 alwaysSucceeds i = do ( do i ; retry ) `orElse` ( return () )
521 -- | always is a variant of alwaysSucceeds in which the invariant is
522 -- expressed as an STM Bool action that must return True. Returning
523 -- False or raising an exception are both treated as invariant failures.
524 always :: STM Bool -> STM ()
525 always i = alwaysSucceeds ( do v <- i
526 if (v) then return () else ( error "Transacional invariant violation" ) )
528 -- |Shared memory locations that support atomic memory transactions.
529 data TVar a = TVar (TVar# RealWorld a)
531 INSTANCE_TYPEABLE1(TVar,tvarTc,"TVar")
533 instance Eq (TVar a) where
534 (TVar tvar1#) == (TVar tvar2#) = sameTVar# tvar1# tvar2#
536 -- |Create a new TVar holding a value supplied
537 newTVar :: a -> STM (TVar a)
538 newTVar val = STM $ \s1# ->
539 case newTVar# val s1# of
540 (# s2#, tvar# #) -> (# s2#, TVar tvar# #)
542 -- |@IO@ version of 'newTVar'. This is useful for creating top-level
543 -- 'TVar's using 'System.IO.Unsafe.unsafePerformIO', because using
544 -- 'atomically' inside 'System.IO.Unsafe.unsafePerformIO' isn't
546 newTVarIO :: a -> IO (TVar a)
547 newTVarIO val = IO $ \s1# ->
548 case newTVar# val s1# of
549 (# s2#, tvar# #) -> (# s2#, TVar tvar# #)
551 -- |Return the current value stored in a TVar
552 readTVar :: TVar a -> STM a
553 readTVar (TVar tvar#) = STM $ \s# -> readTVar# tvar# s#
555 -- |Write the supplied value into a TVar
556 writeTVar :: TVar a -> a -> STM ()
557 writeTVar (TVar tvar#) val = STM $ \s1# ->
558 case writeTVar# tvar# val s1# of
563 %************************************************************************
565 \subsection[mvars]{M-Structures}
567 %************************************************************************
569 M-Vars are rendezvous points for concurrent threads. They begin
570 empty, and any attempt to read an empty M-Var blocks. When an M-Var
571 is written, a single blocked thread may be freed. Reading an M-Var
572 toggles its state from full back to empty. Therefore, any value
573 written to an M-Var may only be read once. Multiple reads and writes
574 are allowed, but there must be at least one read between any two
578 --Defined in IOBase to avoid cycle: data MVar a = MVar (SynchVar# RealWorld a)
580 -- |Create an 'MVar' which is initially empty.
581 newEmptyMVar :: IO (MVar a)
582 newEmptyMVar = IO $ \ s# ->
584 (# s2#, svar# #) -> (# s2#, MVar svar# #)
586 -- |Create an 'MVar' which contains the supplied value.
587 newMVar :: a -> IO (MVar a)
589 newEmptyMVar >>= \ mvar ->
590 putMVar mvar value >>
593 -- |Return the contents of the 'MVar'. If the 'MVar' is currently
594 -- empty, 'takeMVar' will wait until it is full. After a 'takeMVar',
595 -- the 'MVar' is left empty.
597 -- There are two further important properties of 'takeMVar':
599 -- * 'takeMVar' is single-wakeup. That is, if there are multiple
600 -- threads blocked in 'takeMVar', and the 'MVar' becomes full,
601 -- only one thread will be woken up. The runtime guarantees that
602 -- the woken thread completes its 'takeMVar' operation.
604 -- * When multiple threads are blocked on an 'MVar', they are
605 -- woken up in FIFO order. This is useful for providing
606 -- fairness properties of abstractions built using 'MVar's.
608 takeMVar :: MVar a -> IO a
609 takeMVar (MVar mvar#) = IO $ \ s# -> takeMVar# mvar# s#
611 -- |Put a value into an 'MVar'. If the 'MVar' is currently full,
612 -- 'putMVar' will wait until it becomes empty.
614 -- There are two further important properties of 'putMVar':
616 -- * 'putMVar' is single-wakeup. That is, if there are multiple
617 -- threads blocked in 'putMVar', and the 'MVar' becomes empty,
618 -- only one thread will be woken up. The runtime guarantees that
619 -- the woken thread completes its 'putMVar' operation.
621 -- * When multiple threads are blocked on an 'MVar', they are
622 -- woken up in FIFO order. This is useful for providing
623 -- fairness properties of abstractions built using 'MVar's.
625 putMVar :: MVar a -> a -> IO ()
626 putMVar (MVar mvar#) x = IO $ \ s# ->
627 case putMVar# mvar# x s# of
630 -- |A non-blocking version of 'takeMVar'. The 'tryTakeMVar' function
631 -- returns immediately, with 'Nothing' if the 'MVar' was empty, or
632 -- @'Just' a@ if the 'MVar' was full with contents @a@. After 'tryTakeMVar',
633 -- the 'MVar' is left empty.
634 tryTakeMVar :: MVar a -> IO (Maybe a)
635 tryTakeMVar (MVar m) = IO $ \ s ->
636 case tryTakeMVar# m s of
637 (# s, 0#, _ #) -> (# s, Nothing #) -- MVar is empty
638 (# s, _, a #) -> (# s, Just a #) -- MVar is full
640 -- |A non-blocking version of 'putMVar'. The 'tryPutMVar' function
641 -- attempts to put the value @a@ into the 'MVar', returning 'True' if
642 -- it was successful, or 'False' otherwise.
643 tryPutMVar :: MVar a -> a -> IO Bool
644 tryPutMVar (MVar mvar#) x = IO $ \ s# ->
645 case tryPutMVar# mvar# x s# of
646 (# s, 0# #) -> (# s, False #)
647 (# s, _ #) -> (# s, True #)
649 -- |Check whether a given 'MVar' is empty.
651 -- Notice that the boolean value returned is just a snapshot of
652 -- the state of the MVar. By the time you get to react on its result,
653 -- the MVar may have been filled (or emptied) - so be extremely
654 -- careful when using this operation. Use 'tryTakeMVar' instead if possible.
655 isEmptyMVar :: MVar a -> IO Bool
656 isEmptyMVar (MVar mv#) = IO $ \ s# ->
657 case isEmptyMVar# mv# s# of
658 (# s2#, flg #) -> (# s2#, not (flg ==# 0#) #)
660 -- |Add a finalizer to an 'MVar' (GHC only). See "Foreign.ForeignPtr" and
661 -- "System.Mem.Weak" for more about finalizers.
662 addMVarFinalizer :: MVar a -> IO () -> IO ()
663 addMVarFinalizer (MVar m) finalizer =
664 IO $ \s -> case mkWeak# m () finalizer s of { (# s1, w #) -> (# s1, () #) }
666 withMVar :: MVar a -> (a -> IO b) -> IO b
670 b <- catchAny (unblock (io a))
671 (\e -> do putMVar m a; throw e)
677 %************************************************************************
679 \subsection{Thread waiting}
681 %************************************************************************
684 #ifdef mingw32_HOST_OS
686 -- Note: threadWaitRead and threadWaitWrite aren't really functional
687 -- on Win32, but left in there because lib code (still) uses them (the manner
688 -- in which they're used doesn't cause problems on a Win32 platform though.)
690 asyncRead :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
691 asyncRead (I# fd) (I# isSock) (I# len) (Ptr buf) =
692 IO $ \s -> case asyncRead# fd isSock len buf s of
693 (# s, len#, err# #) -> (# s, (I# len#, I# err#) #)
695 asyncWrite :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
696 asyncWrite (I# fd) (I# isSock) (I# len) (Ptr buf) =
697 IO $ \s -> case asyncWrite# fd isSock len buf s of
698 (# s, len#, err# #) -> (# s, (I# len#, I# err#) #)
700 asyncDoProc :: FunPtr (Ptr a -> IO Int) -> Ptr a -> IO Int
701 asyncDoProc (FunPtr proc) (Ptr param) =
702 -- the 'length' value is ignored; simplifies implementation of
703 -- the async*# primops to have them all return the same result.
704 IO $ \s -> case asyncDoProc# proc param s of
705 (# s, len#, err# #) -> (# s, I# err# #)
707 -- to aid the use of these primops by the IO Handle implementation,
708 -- provide the following convenience funs:
710 -- this better be a pinned byte array!
711 asyncReadBA :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int,Int)
712 asyncReadBA fd isSock len off bufB =
713 asyncRead fd isSock len ((Ptr (byteArrayContents# (unsafeCoerce# bufB))) `plusPtr` off)
715 asyncWriteBA :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int,Int)
716 asyncWriteBA fd isSock len off bufB =
717 asyncWrite fd isSock len ((Ptr (byteArrayContents# (unsafeCoerce# bufB))) `plusPtr` off)
721 -- -----------------------------------------------------------------------------
724 -- | Block the current thread until data is available to read on the
725 -- given file descriptor (GHC only).
726 threadWaitRead :: Fd -> IO ()
728 #ifndef mingw32_HOST_OS
729 | threaded = waitForReadEvent fd
731 | otherwise = IO $ \s ->
732 case fromIntegral fd of { I# fd# ->
733 case waitRead# fd# s of { s -> (# s, () #)
736 -- | Block the current thread until data can be written to the
737 -- given file descriptor (GHC only).
738 threadWaitWrite :: Fd -> IO ()
740 #ifndef mingw32_HOST_OS
741 | threaded = waitForWriteEvent fd
743 | otherwise = IO $ \s ->
744 case fromIntegral fd of { I# fd# ->
745 case waitWrite# fd# s of { s -> (# s, () #)
748 -- | Suspends the current thread for a given number of microseconds
751 -- There is no guarantee that the thread will be rescheduled promptly
752 -- when the delay has expired, but the thread will never continue to
753 -- run /earlier/ than specified.
755 threadDelay :: Int -> IO ()
757 | threaded = waitForDelayEvent time
758 | otherwise = IO $ \s ->
759 case fromIntegral time of { I# time# ->
760 case delay# time# s of { s -> (# s, () #)
764 -- | Set the value of returned TVar to True after a given number of
765 -- microseconds. The caveats associated with threadDelay also apply.
767 registerDelay :: Int -> IO (TVar Bool)
769 | threaded = waitForDelayEventSTM usecs
770 | otherwise = error "registerDelay: requires -threaded"
772 foreign import ccall unsafe "rtsSupportsBoundThreads" threaded :: Bool
774 waitForDelayEvent :: Int -> IO ()
775 waitForDelayEvent usecs = do
777 target <- calculateTarget usecs
778 atomicModifyIORef pendingDelays (\xs -> (Delay target m : xs, ()))
782 -- Delays for use in STM
783 waitForDelayEventSTM :: Int -> IO (TVar Bool)
784 waitForDelayEventSTM usecs = do
785 t <- atomically $ newTVar False
786 target <- calculateTarget usecs
787 atomicModifyIORef pendingDelays (\xs -> (DelaySTM target t : xs, ()))
791 calculateTarget :: Int -> IO USecs
792 calculateTarget usecs = do
794 return $ now + (fromIntegral usecs)
797 -- ----------------------------------------------------------------------------
798 -- Threaded RTS implementation of threadWaitRead, threadWaitWrite, threadDelay
800 -- In the threaded RTS, we employ a single IO Manager thread to wait
801 -- for all outstanding IO requests (threadWaitRead,threadWaitWrite)
802 -- and delays (threadDelay).
804 -- We can do this because in the threaded RTS the IO Manager can make
805 -- a non-blocking call to select(), so we don't have to do select() in
806 -- the scheduler as we have to in the non-threaded RTS. We get performance
807 -- benefits from doing it this way, because we only have to restart the select()
808 -- when a new request arrives, rather than doing one select() each time
809 -- around the scheduler loop. Furthermore, the scheduler can be simplified
810 -- by not having to check for completed IO requests.
812 -- Issues, possible problems:
814 -- - we might want bound threads to just do the blocking
815 -- operation rather than communicating with the IO manager
816 -- thread. This would prevent simgle-threaded programs which do
817 -- IO from requiring multiple OS threads. However, it would also
818 -- prevent bound threads waiting on IO from being killed or sent
821 -- - Apprently exec() doesn't work on Linux in a multithreaded program.
822 -- I couldn't repeat this.
824 -- - How do we handle signal delivery in the multithreaded RTS?
826 -- - forkProcess will kill the IO manager thread. Let's just
827 -- hope we don't need to do any blocking IO between fork & exec.
829 #ifndef mingw32_HOST_OS
831 = Read {-# UNPACK #-} !Fd {-# UNPACK #-} !(MVar ())
832 | Write {-# UNPACK #-} !Fd {-# UNPACK #-} !(MVar ())
836 = Delay {-# UNPACK #-} !USecs {-# UNPACK #-} !(MVar ())
837 | DelaySTM {-# UNPACK #-} !USecs {-# UNPACK #-} !(TVar Bool)
839 #ifndef mingw32_HOST_OS
840 pendingEvents :: IORef [IOReq]
842 pendingDelays :: IORef [DelayReq]
843 -- could use a strict list or array here
844 {-# NOINLINE pendingEvents #-}
845 {-# NOINLINE pendingDelays #-}
846 (pendingEvents,pendingDelays) = unsafePerformIO $ do
851 -- the first time we schedule an IO request, the service thread
852 -- will be created (cool, huh?)
854 ensureIOManagerIsRunning :: IO ()
855 ensureIOManagerIsRunning
856 | threaded = seq pendingEvents $ return ()
857 | otherwise = return ()
859 insertDelay :: DelayReq -> [DelayReq] -> [DelayReq]
860 insertDelay d [] = [d]
861 insertDelay d1 ds@(d2 : rest)
862 | delayTime d1 <= delayTime d2 = d1 : ds
863 | otherwise = d2 : insertDelay d1 rest
865 delayTime :: DelayReq -> USecs
866 delayTime (Delay t _) = t
867 delayTime (DelaySTM t _) = t
871 -- XXX: move into GHC.IOBase from Data.IORef?
872 atomicModifyIORef :: IORef a -> (a -> (a,b)) -> IO b
873 atomicModifyIORef (IORef (STRef r#)) f = IO $ \s -> atomicModifyMutVar# r# f s
875 foreign import ccall unsafe "getUSecOfDay"
876 getUSecOfDay :: IO USecs
878 prodding :: IORef Bool
879 {-# NOINLINE prodding #-}
880 prodding = unsafePerformIO (newIORef False)
882 prodServiceThread :: IO ()
883 prodServiceThread = do
884 was_set <- atomicModifyIORef prodding (\a -> (True,a))
885 if (not (was_set)) then wakeupIOManager else return ()
887 #ifdef mingw32_HOST_OS
888 -- ----------------------------------------------------------------------------
889 -- Windows IO manager thread
891 startIOManagerThread :: IO ()
892 startIOManagerThread = do
893 wakeup <- c_getIOManagerEvent
894 forkIO $ service_loop wakeup []
897 service_loop :: HANDLE -- read end of pipe
898 -> [DelayReq] -- current delay requests
901 service_loop wakeup old_delays = do
902 -- pick up new delay requests
903 new_delays <- atomicModifyIORef pendingDelays (\a -> ([],a))
904 let delays = foldr insertDelay old_delays new_delays
907 (delays', timeout) <- getDelay now delays
909 r <- c_WaitForSingleObject wakeup timeout
911 0xffffffff -> do c_maperrno; throwErrno "service_loop"
913 r <- c_readIOManagerEvent
916 _ | r == io_MANAGER_WAKEUP -> return False
917 _ | r == io_MANAGER_DIE -> return True
918 0 -> return False -- spurious wakeup
919 r -> do start_console_handler (r `shiftR` 1); return False
922 else service_cont wakeup delays'
924 _other -> service_cont wakeup delays' -- probably timeout
926 service_cont wakeup delays = do
927 atomicModifyIORef prodding (\_ -> (False,False))
928 service_loop wakeup delays
930 -- must agree with rts/win32/ThrIOManager.c
931 io_MANAGER_WAKEUP = 0xffffffff :: Word32
932 io_MANAGER_DIE = 0xfffffffe :: Word32
938 -- these are sent to Services only.
941 deriving (Eq, Ord, Enum, Show, Read, Typeable)
943 start_console_handler :: Word32 -> IO ()
944 start_console_handler r =
945 case toWin32ConsoleEvent r of
946 Just x -> withMVar win32ConsoleHandler $ \handler -> do
951 toWin32ConsoleEvent ev =
953 0 {- CTRL_C_EVENT-} -> Just ControlC
954 1 {- CTRL_BREAK_EVENT-} -> Just Break
955 2 {- CTRL_CLOSE_EVENT-} -> Just Close
956 5 {- CTRL_LOGOFF_EVENT-} -> Just Logoff
957 6 {- CTRL_SHUTDOWN_EVENT-} -> Just Shutdown
960 win32ConsoleHandler :: MVar (ConsoleEvent -> IO ())
961 win32ConsoleHandler = unsafePerformIO (newMVar (error "win32ConsoleHandler"))
963 stick :: IORef HANDLE
964 {-# NOINLINE stick #-}
965 stick = unsafePerformIO (newIORef nullPtr)
968 hdl <- readIORef stick
969 c_sendIOManagerEvent io_MANAGER_WAKEUP
971 -- Walk the queue of pending delays, waking up any that have passed
972 -- and return the smallest delay to wait for. The queue of pending
973 -- delays is kept ordered.
974 getDelay :: USecs -> [DelayReq] -> IO ([DelayReq], DWORD)
975 getDelay now [] = return ([], iNFINITE)
976 getDelay now all@(d : rest)
978 Delay time m | now >= time -> do
981 DelaySTM time t | now >= time -> do
982 atomically $ writeTVar t True
985 -- delay is in millisecs for WaitForSingleObject
986 let micro_seconds = delayTime d - now
987 milli_seconds = (micro_seconds + 999) `div` 1000
988 in return (all, fromIntegral milli_seconds)
990 -- ToDo: this just duplicates part of System.Win32.Types, which isn't
991 -- available yet. We should move some Win32 functionality down here,
992 -- maybe as part of the grand reorganisation of the base package...
996 iNFINITE = 0xFFFFFFFF :: DWORD -- urgh
998 foreign import ccall unsafe "getIOManagerEvent" -- in the RTS (ThrIOManager.c)
999 c_getIOManagerEvent :: IO HANDLE
1001 foreign import ccall unsafe "readIOManagerEvent" -- in the RTS (ThrIOManager.c)
1002 c_readIOManagerEvent :: IO Word32
1004 foreign import ccall unsafe "sendIOManagerEvent" -- in the RTS (ThrIOManager.c)
1005 c_sendIOManagerEvent :: Word32 -> IO ()
1007 foreign import ccall unsafe "maperrno" -- in Win32Utils.c
1010 foreign import stdcall "WaitForSingleObject"
1011 c_WaitForSingleObject :: HANDLE -> DWORD -> IO DWORD
1014 -- ----------------------------------------------------------------------------
1015 -- Unix IO manager thread, using select()
1017 startIOManagerThread :: IO ()
1018 startIOManagerThread = do
1019 allocaArray 2 $ \fds -> do
1020 throwErrnoIfMinus1 "startIOManagerThread" (c_pipe fds)
1021 rd_end <- peekElemOff fds 0
1022 wr_end <- peekElemOff fds 1
1023 writeIORef stick (fromIntegral wr_end)
1024 c_setIOManagerPipe wr_end
1026 allocaBytes sizeofFdSet $ \readfds -> do
1027 allocaBytes sizeofFdSet $ \writefds -> do
1028 allocaBytes sizeofTimeVal $ \timeval -> do
1029 service_loop (fromIntegral rd_end) readfds writefds timeval [] []
1033 :: Fd -- listen to this for wakeup calls
1040 service_loop wakeup readfds writefds ptimeval old_reqs old_delays = do
1042 -- pick up new IO requests
1043 new_reqs <- atomicModifyIORef pendingEvents (\a -> ([],a))
1044 let reqs = new_reqs ++ old_reqs
1046 -- pick up new delay requests
1047 new_delays <- atomicModifyIORef pendingDelays (\a -> ([],a))
1048 let delays = foldr insertDelay old_delays new_delays
1050 -- build the FDSets for select()
1053 fdSet wakeup readfds
1054 maxfd <- buildFdSets 0 readfds writefds reqs
1056 -- perform the select()
1057 let do_select delays = do
1058 -- check the current time and wake up any thread in
1059 -- threadDelay whose timeout has expired. Also find the
1060 -- timeout value for the select() call.
1062 (delays', timeout) <- getDelay now ptimeval delays
1064 res <- c_select (fromIntegral ((max wakeup maxfd)+1)) readfds writefds
1070 _ | err == eINTR -> do_select delays'
1071 -- EINTR: just redo the select()
1072 _ | err == eBADF -> return (True, delays)
1073 -- EBADF: one of the file descriptors is closed or bad,
1074 -- we don't know which one, so wake everyone up.
1075 _ | otherwise -> throwErrno "select"
1076 -- otherwise (ENOMEM or EINVAL) something has gone
1077 -- wrong; report the error.
1079 return (False,delays')
1081 (wakeup_all,delays') <- do_select delays
1084 if wakeup_all then return False
1086 b <- fdIsSet wakeup readfds
1089 else alloca $ \p -> do
1090 c_read (fromIntegral wakeup) p 1; return ()
1093 _ | s == io_MANAGER_WAKEUP -> return False
1094 _ | s == io_MANAGER_DIE -> return True
1095 _ -> withMVar signalHandlerLock $ \_ -> do
1096 handler_tbl <- peek handlers
1097 sp <- peekElemOff handler_tbl (fromIntegral s)
1098 io <- deRefStablePtr sp
1102 if exit then return () else do
1104 atomicModifyIORef prodding (\_ -> (False,False))
1106 reqs' <- if wakeup_all then do wakeupAll reqs; return []
1107 else completeRequests reqs readfds writefds []
1109 service_loop wakeup readfds writefds ptimeval reqs' delays'
1111 io_MANAGER_WAKEUP = 0xff :: CChar
1112 io_MANAGER_DIE = 0xfe :: CChar
1115 {-# NOINLINE stick #-}
1116 stick = unsafePerformIO (newIORef 0)
1118 wakeupIOManager :: IO ()
1119 wakeupIOManager = do
1120 fd <- readIORef stick
1121 with io_MANAGER_WAKEUP $ \pbuf -> do
1122 c_write (fromIntegral fd) pbuf 1; return ()
1124 -- Lock used to protect concurrent access to signal_handlers. Symptom of
1125 -- this race condition is #1922, although that bug was on Windows a similar
1126 -- bug also exists on Unix.
1127 signalHandlerLock :: MVar ()
1128 signalHandlerLock = unsafePerformIO (newMVar ())
1130 foreign import ccall "&signal_handlers" handlers :: Ptr (Ptr (StablePtr (IO ())))
1132 foreign import ccall "setIOManagerPipe"
1133 c_setIOManagerPipe :: CInt -> IO ()
1135 -- -----------------------------------------------------------------------------
1138 buildFdSets maxfd readfds writefds [] = return maxfd
1139 buildFdSets maxfd readfds writefds (Read fd m : reqs)
1140 | fd >= fD_SETSIZE = error "buildFdSets: file descriptor out of range"
1143 buildFdSets (max maxfd fd) readfds writefds reqs
1144 buildFdSets maxfd readfds writefds (Write fd m : reqs)
1145 | fd >= fD_SETSIZE = error "buildFdSets: file descriptor out of range"
1148 buildFdSets (max maxfd fd) readfds writefds reqs
1150 completeRequests [] _ _ reqs' = return reqs'
1151 completeRequests (Read fd m : reqs) readfds writefds reqs' = do
1152 b <- fdIsSet fd readfds
1154 then do putMVar m (); completeRequests reqs readfds writefds reqs'
1155 else completeRequests reqs readfds writefds (Read fd m : reqs')
1156 completeRequests (Write fd m : reqs) readfds writefds reqs' = do
1157 b <- fdIsSet fd writefds
1159 then do putMVar m (); completeRequests reqs readfds writefds reqs'
1160 else completeRequests reqs readfds writefds (Write fd m : reqs')
1162 wakeupAll [] = return ()
1163 wakeupAll (Read fd m : reqs) = do putMVar m (); wakeupAll reqs
1164 wakeupAll (Write fd m : reqs) = do putMVar m (); wakeupAll reqs
1166 waitForReadEvent :: Fd -> IO ()
1167 waitForReadEvent fd = do
1169 atomicModifyIORef pendingEvents (\xs -> (Read fd m : xs, ()))
1173 waitForWriteEvent :: Fd -> IO ()
1174 waitForWriteEvent fd = do
1176 atomicModifyIORef pendingEvents (\xs -> (Write fd m : xs, ()))
1180 -- -----------------------------------------------------------------------------
1183 -- Walk the queue of pending delays, waking up any that have passed
1184 -- and return the smallest delay to wait for. The queue of pending
1185 -- delays is kept ordered.
1186 getDelay :: USecs -> Ptr CTimeVal -> [DelayReq] -> IO ([DelayReq], Ptr CTimeVal)
1187 getDelay now ptimeval [] = return ([],nullPtr)
1188 getDelay now ptimeval all@(d : rest)
1190 Delay time m | now >= time -> do
1192 getDelay now ptimeval rest
1193 DelaySTM time t | now >= time -> do
1194 atomically $ writeTVar t True
1195 getDelay now ptimeval rest
1197 setTimevalTicks ptimeval (delayTime d - now)
1198 return (all,ptimeval)
1200 newtype CTimeVal = CTimeVal ()
1202 foreign import ccall unsafe "sizeofTimeVal"
1203 sizeofTimeVal :: Int
1205 foreign import ccall unsafe "setTimevalTicks"
1206 setTimevalTicks :: Ptr CTimeVal -> USecs -> IO ()
1209 On Win32 we're going to have a single Pipe, and a
1210 waitForSingleObject with the delay time. For signals, we send a
1211 byte down the pipe just like on Unix.
1214 -- ----------------------------------------------------------------------------
1215 -- select() interface
1217 -- ToDo: move to System.Posix.Internals?
1219 newtype CFdSet = CFdSet ()
1221 foreign import ccall safe "select"
1222 c_select :: CInt -> Ptr CFdSet -> Ptr CFdSet -> Ptr CFdSet -> Ptr CTimeVal
1225 foreign import ccall unsafe "hsFD_SETSIZE"
1226 c_fD_SETSIZE :: CInt
1229 fD_SETSIZE = fromIntegral c_fD_SETSIZE
1231 foreign import ccall unsafe "hsFD_CLR"
1232 c_fdClr :: CInt -> Ptr CFdSet -> IO ()
1234 fdClr :: Fd -> Ptr CFdSet -> IO ()
1235 fdClr (Fd fd) fdset = c_fdClr fd fdset
1237 foreign import ccall unsafe "hsFD_ISSET"
1238 c_fdIsSet :: CInt -> Ptr CFdSet -> IO CInt
1240 fdIsSet :: Fd -> Ptr CFdSet -> IO CInt
1241 fdIsSet (Fd fd) fdset = c_fdIsSet fd fdset
1243 foreign import ccall unsafe "hsFD_SET"
1244 c_fdSet :: CInt -> Ptr CFdSet -> IO ()
1246 fdSet :: Fd -> Ptr CFdSet -> IO ()
1247 fdSet (Fd fd) fdset = c_fdSet fd fdset
1249 foreign import ccall unsafe "hsFD_ZERO"
1250 fdZero :: Ptr CFdSet -> IO ()
1252 foreign import ccall unsafe "sizeof_fd_set"
1257 reportStackOverflow :: IO a
1258 reportStackOverflow = do callStackOverflowHook; return undefined
1260 reportError :: SomeException -> IO a
1262 handler <- getUncaughtExceptionHandler
1266 -- SUP: Are the hooks allowed to re-enter Haskell land? If so, remove
1267 -- the unsafe below.
1268 foreign import ccall unsafe "stackOverflow"
1269 callStackOverflowHook :: IO ()
1271 {-# NOINLINE uncaughtExceptionHandler #-}
1272 uncaughtExceptionHandler :: IORef (SomeException -> IO ())
1273 uncaughtExceptionHandler = unsafePerformIO (newIORef defaultHandler)
1275 defaultHandler :: SomeException -> IO ()
1276 defaultHandler se@(SomeException ex) = do
1277 (hFlush stdout) `catchAny` (\ _ -> return ())
1278 let msg = case cast ex of
1279 Just Deadlock -> "no threads to run: infinite loop or deadlock?"
1280 _ -> case cast ex of
1281 Just (ErrorCall s) -> s
1282 _ -> showsPrec 0 se ""
1283 withCString "%s" $ \cfmt ->
1284 withCString msg $ \cmsg ->
1285 errorBelch cfmt cmsg
1287 -- don't use errorBelch() directly, because we cannot call varargs functions
1289 foreign import ccall unsafe "HsBase.h errorBelch2"
1290 errorBelch :: CString -> CString -> IO ()
1292 setUncaughtExceptionHandler :: (SomeException -> IO ()) -> IO ()
1293 setUncaughtExceptionHandler = writeIORef uncaughtExceptionHandler
1295 getUncaughtExceptionHandler :: IO (SomeException -> IO ())
1296 getUncaughtExceptionHandler = readIORef uncaughtExceptionHandler