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 ()
43 , threadDelay -- :: Int -> IO ()
44 , registerDelay -- :: Int -> IO (TVar Bool)
45 , threadWaitRead -- :: Int -> IO ()
46 , threadWaitWrite -- :: Int -> IO ()
50 , newMVar -- :: a -> IO (MVar a)
51 , newEmptyMVar -- :: IO (MVar a)
52 , takeMVar -- :: MVar a -> IO a
53 , putMVar -- :: MVar a -> a -> IO ()
54 , tryTakeMVar -- :: MVar a -> IO (Maybe a)
55 , tryPutMVar -- :: MVar a -> a -> IO Bool
56 , isEmptyMVar -- :: MVar a -> IO Bool
57 , addMVarFinalizer -- :: MVar a -> IO () -> IO ()
61 , atomically -- :: STM a -> IO a
63 , orElse -- :: STM a -> STM a -> STM a
64 , catchSTM -- :: STM a -> (Exception -> STM a) -> STM a
65 , alwaysSucceeds -- :: STM a -> STM ()
66 , always -- :: STM Bool -> STM ()
68 , newTVar -- :: a -> STM (TVar a)
69 , newTVarIO -- :: a -> STM (TVar a)
70 , readTVar -- :: TVar a -> STM a
71 , writeTVar -- :: a -> TVar a -> STM ()
72 , unsafeIOToSTM -- :: IO a -> STM a
75 #ifdef mingw32_HOST_OS
76 , asyncRead -- :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
77 , asyncWrite -- :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
78 , asyncDoProc -- :: FunPtr (Ptr a -> IO Int) -> Ptr a -> IO Int
80 , asyncReadBA -- :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int, Int)
81 , asyncWriteBA -- :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int, Int)
84 #ifndef mingw32_HOST_OS
88 , ensureIOManagerIsRunning
90 #ifdef mingw32_HOST_OS
97 import System.Posix.Types
98 #ifndef mingw32_HOST_OS
99 import System.Posix.Internals
105 import {-# SOURCE #-} GHC.TopHandler ( reportError, reportStackOverflow )
112 import GHC.Num ( Num(..) )
113 import GHC.Real ( fromIntegral, div )
114 #ifndef mingw32_HOST_OS
115 import GHC.Base ( Int(..) )
117 #ifdef mingw32_HOST_OS
118 import GHC.Read ( Read )
119 import GHC.Enum ( Enum )
122 import GHC.Pack ( packCString# )
123 import GHC.Ptr ( Ptr(..), plusPtr, FunPtr(..) )
125 import GHC.Show ( Show(..), showString )
128 infixr 0 `par`, `pseq`
131 %************************************************************************
133 \subsection{@ThreadId@, @par@, and @fork@}
135 %************************************************************************
138 data ThreadId = ThreadId ThreadId# deriving( Typeable )
139 -- ToDo: data ThreadId = ThreadId (Weak ThreadId#)
140 -- But since ThreadId# is unlifted, the Weak type must use open
143 A 'ThreadId' is an abstract type representing a handle to a thread.
144 'ThreadId' is an instance of 'Eq', 'Ord' and 'Show', where
145 the 'Ord' instance implements an arbitrary total ordering over
146 'ThreadId's. The 'Show' instance lets you convert an arbitrary-valued
147 'ThreadId' to string form; showing a 'ThreadId' value is occasionally
148 useful when debugging or diagnosing the behaviour of a concurrent
151 /Note/: in GHC, if you have a 'ThreadId', you essentially have
152 a pointer to the thread itself. This means the thread itself can\'t be
153 garbage collected until you drop the 'ThreadId'.
154 This misfeature will hopefully be corrected at a later date.
156 /Note/: Hugs does not provide any operations on other threads;
157 it defines 'ThreadId' as a synonym for ().
160 instance Show ThreadId where
162 showString "ThreadId " .
163 showsPrec d (getThreadId (id2TSO t))
165 foreign import ccall unsafe "rts_getThreadId" getThreadId :: ThreadId# -> CInt
167 id2TSO :: ThreadId -> ThreadId#
168 id2TSO (ThreadId t) = t
170 foreign import ccall unsafe "cmp_thread" cmp_thread :: ThreadId# -> ThreadId# -> CInt
173 cmpThread :: ThreadId -> ThreadId -> Ordering
175 case cmp_thread (id2TSO t1) (id2TSO t2) of
180 instance Eq ThreadId where
182 case t1 `cmpThread` t2 of
186 instance Ord ThreadId where
190 Sparks off a new thread to run the 'IO' computation passed as the
191 first argument, and returns the 'ThreadId' of the newly created
194 The new thread will be a lightweight thread; if you want to use a foreign
195 library that uses thread-local storage, use 'Control.Concurrent.forkOS' instead.
197 GHC note: the new thread inherits the /blocked/ state of the parent
198 (see 'Control.Exception.block').
200 forkIO :: IO () -> IO ThreadId
201 forkIO action = IO $ \ s ->
202 case (fork# action_plus s) of (# s1, id #) -> (# s1, ThreadId id #)
204 action_plus = catchException action childHandler
207 Like 'forkIO', but lets you specify on which CPU the thread is
208 created. Unlike a `forkIO` thread, a thread created by `forkOnIO`
209 will stay on the same CPU for its entire lifetime (`forkIO` threads
210 can migrate between CPUs according to the scheduling policy).
211 `forkOnIO` is useful for overriding the scheduling policy when you
212 know in advance how best to distribute the threads.
214 The `Int` argument specifies the CPU number; it is interpreted modulo
215 'numCapabilities' (note that it actually specifies a capability number
216 rather than a CPU number, but to a first approximation the two are
219 forkOnIO :: Int -> IO () -> IO ThreadId
220 forkOnIO (I# cpu) action = IO $ \ s ->
221 case (forkOn# cpu action_plus s) of (# s1, id #) -> (# s1, ThreadId id #)
223 action_plus = catchException action childHandler
225 -- | the value passed to the @+RTS -N@ flag. This is the number of
226 -- Haskell threads that can run truly simultaneously at any given
227 -- time, and is typically set to the number of physical CPU cores on
229 numCapabilities :: Int
230 numCapabilities = unsafePerformIO $ do
231 n <- peek n_capabilities
232 return (fromIntegral n)
234 foreign import ccall "&n_capabilities" n_capabilities :: Ptr CInt
236 childHandler :: Exception -> IO ()
237 childHandler err = catchException (real_handler err) childHandler
239 real_handler :: Exception -> IO ()
242 -- ignore thread GC and killThread exceptions:
243 BlockedOnDeadMVar -> return ()
244 BlockedIndefinitely -> return ()
245 AsyncException ThreadKilled -> return ()
247 -- report all others:
248 AsyncException StackOverflow -> reportStackOverflow
249 other -> reportError other
251 {- | 'killThread' terminates the given thread (GHC only).
252 Any work already done by the thread isn\'t
253 lost: the computation is suspended until required by another thread.
254 The memory used by the thread will be garbage collected if it isn\'t
255 referenced from anywhere. The 'killThread' function is defined in
258 > killThread tid = throwTo tid (AsyncException ThreadKilled)
261 killThread :: ThreadId -> IO ()
262 killThread tid = throwTo tid (AsyncException ThreadKilled)
264 {- | 'throwTo' raises an arbitrary exception in the target thread (GHC only).
266 'throwTo' does not return until the exception has been raised in the
268 The calling thread can thus be certain that the target
269 thread has received the exception. This is a useful property to know
270 when dealing with race conditions: eg. if there are two threads that
271 can kill each other, it is guaranteed that only one of the threads
272 will get to kill the other.
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 'block' 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 8 of the paper.
285 Like any blocking operation, 'throwTo' is therefore interruptible (see Section 4.3 of
288 There is currently no guarantee that the exception delivered by 'throwTo' will be
289 delivered at the first possible opportunity. In particular, if a thread may
290 unblock and then re-block exceptions (using 'unblock' and 'block') without receiving
291 a pending 'throwTo'. This is arguably undesirable behaviour.
294 throwTo :: ThreadId -> Exception -> IO ()
295 throwTo (ThreadId id) ex = IO $ \ s ->
296 case (killThread# id ex s) of s1 -> (# s1, () #)
298 -- | Returns the 'ThreadId' of the calling thread (GHC only).
299 myThreadId :: IO ThreadId
300 myThreadId = IO $ \s ->
301 case (myThreadId# s) of (# s1, id #) -> (# s1, ThreadId id #)
304 -- |The 'yield' action allows (forces, in a co-operative multitasking
305 -- implementation) a context-switch to any other currently runnable
306 -- threads (if any), and is occasionally useful when implementing
307 -- concurrency abstractions.
310 case (yield# s) of s1 -> (# s1, () #)
312 {- | 'labelThread' stores a string as identifier for this thread if
313 you built a RTS with debugging support. This identifier will be used in
314 the debugging output to make distinction of different threads easier
315 (otherwise you only have the thread state object\'s address in the heap).
317 Other applications like the graphical Concurrent Haskell Debugger
318 (<http://www.informatik.uni-kiel.de/~fhu/chd/>) may choose to overload
319 'labelThread' for their purposes as well.
322 labelThread :: ThreadId -> String -> IO ()
323 labelThread (ThreadId t) str = IO $ \ s ->
324 let ps = packCString# str
325 adr = byteArrayContents# ps in
326 case (labelThread# t adr s) of s1 -> (# s1, () #)
328 -- Nota Bene: 'pseq' used to be 'seq'
329 -- but 'seq' is now defined in PrelGHC
331 -- "pseq" is defined a bit weirdly (see below)
333 -- The reason for the strange "lazy" call is that
334 -- it fools the compiler into thinking that pseq and par are non-strict in
335 -- their second argument (even if it inlines pseq at the call site).
336 -- If it thinks pseq is strict in "y", then it often evaluates
337 -- "y" before "x", which is totally wrong.
341 pseq x y = x `seq` lazy y
345 par x y = case (par# x) of { _ -> lazy y }
349 %************************************************************************
351 \subsection[stm]{Transactional heap operations}
353 %************************************************************************
355 TVars are shared memory locations which support atomic memory
359 -- |A monad supporting atomic memory transactions.
360 newtype STM a = STM (State# RealWorld -> (# State# RealWorld, a #))
362 unSTM :: STM a -> (State# RealWorld -> (# State# RealWorld, a #))
365 INSTANCE_TYPEABLE1(STM,stmTc,"STM")
367 instance Functor STM where
368 fmap f x = x >>= (return . f)
370 instance Monad STM where
371 {-# INLINE return #-}
375 return x = returnSTM x
376 m >>= k = bindSTM m k
378 bindSTM :: STM a -> (a -> STM b) -> STM b
379 bindSTM (STM m) k = STM ( \s ->
381 (# new_s, a #) -> unSTM (k a) new_s
384 thenSTM :: STM a -> STM b -> STM b
385 thenSTM (STM m) k = STM ( \s ->
387 (# new_s, a #) -> unSTM k new_s
390 returnSTM :: a -> STM a
391 returnSTM x = STM (\s -> (# s, x #))
393 -- | Unsafely performs IO in the STM monad.
394 unsafeIOToSTM :: IO a -> STM a
395 unsafeIOToSTM (IO m) = STM m
397 -- |Perform a series of STM actions atomically.
399 -- You cannot use 'atomically' inside an 'unsafePerformIO' or 'unsafeInterleaveIO'.
400 -- Any attempt to do so will result in a runtime error. (Reason: allowing
401 -- this would effectively allow a transaction inside a transaction, depending
402 -- on exactly when the thunk is evaluated.)
404 -- However, see 'newTVarIO', which can be called inside 'unsafePerformIO',
405 -- and which allows top-level TVars to be allocated.
407 atomically :: STM a -> IO a
408 atomically (STM m) = IO (\s -> (atomically# m) s )
410 -- |Retry execution of the current memory transaction because it has seen
411 -- values in TVars which mean that it should not continue (e.g. the TVars
412 -- represent a shared buffer that is now empty). The implementation may
413 -- block the thread until one of the TVars that it has read from has been
414 -- udpated. (GHC only)
416 retry = STM $ \s# -> retry# s#
418 -- |Compose two alternative STM actions (GHC only). If the first action
419 -- completes without retrying then it forms the result of the orElse.
420 -- Otherwise, if the first action retries, then the second action is
421 -- tried in its place. If both actions retry then the orElse as a
423 orElse :: STM a -> STM a -> STM a
424 orElse (STM m) e = STM $ \s -> catchRetry# m (unSTM e) s
426 -- |Exception handling within STM actions.
427 catchSTM :: STM a -> (Exception -> STM a) -> STM a
428 catchSTM (STM m) k = STM $ \s -> catchSTM# m (\ex -> unSTM (k ex)) s
430 -- | Low-level primitive on which always and alwaysSucceeds are built.
431 -- checkInv differs form these in that (i) the invariant is not
432 -- checked when checkInv is called, only at the end of this and
433 -- subsequent transcations, (ii) the invariant failure is indicated
434 -- by raising an exception.
435 checkInv :: STM a -> STM ()
436 checkInv (STM m) = STM (\s -> (check# m) s)
438 -- | alwaysSucceeds adds a new invariant that must be true when passed
439 -- to alwaysSucceeds, at the end of the current transaction, and at
440 -- the end of every subsequent transaction. If it fails at any
441 -- of those points then the transaction violating it is aborted
442 -- and the exception raised by the invariant is propagated.
443 alwaysSucceeds :: STM a -> STM ()
444 alwaysSucceeds i = do ( do i ; retry ) `orElse` ( return () )
447 -- | always is a variant of alwaysSucceeds in which the invariant is
448 -- expressed as an STM Bool action that must return True. Returning
449 -- False or raising an exception are both treated as invariant failures.
450 always :: STM Bool -> STM ()
451 always i = alwaysSucceeds ( do v <- i
452 if (v) then return () else ( error "Transacional invariant violation" ) )
454 -- |Shared memory locations that support atomic memory transactions.
455 data TVar a = TVar (TVar# RealWorld a)
457 INSTANCE_TYPEABLE1(TVar,tvarTc,"TVar")
459 instance Eq (TVar a) where
460 (TVar tvar1#) == (TVar tvar2#) = sameTVar# tvar1# tvar2#
462 -- |Create a new TVar holding a value supplied
463 newTVar :: a -> STM (TVar a)
464 newTVar val = STM $ \s1# ->
465 case newTVar# val s1# of
466 (# s2#, tvar# #) -> (# s2#, TVar tvar# #)
468 -- |@IO@ version of 'newTVar'. This is useful for creating top-level
469 -- 'TVar's using 'System.IO.Unsafe.unsafePerformIO', because using
470 -- 'atomically' inside 'System.IO.Unsafe.unsafePerformIO' isn't
472 newTVarIO :: a -> IO (TVar a)
473 newTVarIO val = IO $ \s1# ->
474 case newTVar# val s1# of
475 (# s2#, tvar# #) -> (# s2#, TVar tvar# #)
477 -- |Return the current value stored in a TVar
478 readTVar :: TVar a -> STM a
479 readTVar (TVar tvar#) = STM $ \s# -> readTVar# tvar# s#
481 -- |Write the supplied value into a TVar
482 writeTVar :: TVar a -> a -> STM ()
483 writeTVar (TVar tvar#) val = STM $ \s1# ->
484 case writeTVar# tvar# val s1# of
489 %************************************************************************
491 \subsection[mvars]{M-Structures}
493 %************************************************************************
495 M-Vars are rendezvous points for concurrent threads. They begin
496 empty, and any attempt to read an empty M-Var blocks. When an M-Var
497 is written, a single blocked thread may be freed. Reading an M-Var
498 toggles its state from full back to empty. Therefore, any value
499 written to an M-Var may only be read once. Multiple reads and writes
500 are allowed, but there must be at least one read between any two
504 --Defined in IOBase to avoid cycle: data MVar a = MVar (SynchVar# RealWorld a)
506 -- |Create an 'MVar' which is initially empty.
507 newEmptyMVar :: IO (MVar a)
508 newEmptyMVar = IO $ \ s# ->
510 (# s2#, svar# #) -> (# s2#, MVar svar# #)
512 -- |Create an 'MVar' which contains the supplied value.
513 newMVar :: a -> IO (MVar a)
515 newEmptyMVar >>= \ mvar ->
516 putMVar mvar value >>
519 -- |Return the contents of the 'MVar'. If the 'MVar' is currently
520 -- empty, 'takeMVar' will wait until it is full. After a 'takeMVar',
521 -- the 'MVar' is left empty.
523 -- There are two further important properties of 'takeMVar':
525 -- * 'takeMVar' is single-wakeup. That is, if there are multiple
526 -- threads blocked in 'takeMVar', and the 'MVar' becomes full,
527 -- only one thread will be woken up. The runtime guarantees that
528 -- the woken thread completes its 'takeMVar' operation.
530 -- * When multiple threads are blocked on an 'MVar', they are
531 -- woken up in FIFO order. This is useful for providing
532 -- fairness properties of abstractions built using 'MVar's.
534 takeMVar :: MVar a -> IO a
535 takeMVar (MVar mvar#) = IO $ \ s# -> takeMVar# mvar# s#
537 -- |Put a value into an 'MVar'. If the 'MVar' is currently full,
538 -- 'putMVar' will wait until it becomes empty.
540 -- There are two further important properties of 'putMVar':
542 -- * 'putMVar' is single-wakeup. That is, if there are multiple
543 -- threads blocked in 'putMVar', and the 'MVar' becomes empty,
544 -- only one thread will be woken up. The runtime guarantees that
545 -- the woken thread completes its 'putMVar' operation.
547 -- * When multiple threads are blocked on an 'MVar', they are
548 -- woken up in FIFO order. This is useful for providing
549 -- fairness properties of abstractions built using 'MVar's.
551 putMVar :: MVar a -> a -> IO ()
552 putMVar (MVar mvar#) x = IO $ \ s# ->
553 case putMVar# mvar# x s# of
556 -- |A non-blocking version of 'takeMVar'. The 'tryTakeMVar' function
557 -- returns immediately, with 'Nothing' if the 'MVar' was empty, or
558 -- @'Just' a@ if the 'MVar' was full with contents @a@. After 'tryTakeMVar',
559 -- the 'MVar' is left empty.
560 tryTakeMVar :: MVar a -> IO (Maybe a)
561 tryTakeMVar (MVar m) = IO $ \ s ->
562 case tryTakeMVar# m s of
563 (# s, 0#, _ #) -> (# s, Nothing #) -- MVar is empty
564 (# s, _, a #) -> (# s, Just a #) -- MVar is full
566 -- |A non-blocking version of 'putMVar'. The 'tryPutMVar' function
567 -- attempts to put the value @a@ into the 'MVar', returning 'True' if
568 -- it was successful, or 'False' otherwise.
569 tryPutMVar :: MVar a -> a -> IO Bool
570 tryPutMVar (MVar mvar#) x = IO $ \ s# ->
571 case tryPutMVar# mvar# x s# of
572 (# s, 0# #) -> (# s, False #)
573 (# s, _ #) -> (# s, True #)
575 -- |Check whether a given 'MVar' is empty.
577 -- Notice that the boolean value returned is just a snapshot of
578 -- the state of the MVar. By the time you get to react on its result,
579 -- the MVar may have been filled (or emptied) - so be extremely
580 -- careful when using this operation. Use 'tryTakeMVar' instead if possible.
581 isEmptyMVar :: MVar a -> IO Bool
582 isEmptyMVar (MVar mv#) = IO $ \ s# ->
583 case isEmptyMVar# mv# s# of
584 (# s2#, flg #) -> (# s2#, not (flg ==# 0#) #)
586 -- |Add a finalizer to an 'MVar' (GHC only). See "Foreign.ForeignPtr" and
587 -- "System.Mem.Weak" for more about finalizers.
588 addMVarFinalizer :: MVar a -> IO () -> IO ()
589 addMVarFinalizer (MVar m) finalizer =
590 IO $ \s -> case mkWeak# m () finalizer s of { (# s1, w #) -> (# s1, () #) }
592 withMVar :: MVar a -> (a -> IO b) -> IO b
596 b <- catchException (unblock (io a))
597 (\e -> do putMVar m a; throw e)
603 %************************************************************************
605 \subsection{Thread waiting}
607 %************************************************************************
610 #ifdef mingw32_HOST_OS
612 -- Note: threadWaitRead and threadWaitWrite aren't really functional
613 -- on Win32, but left in there because lib code (still) uses them (the manner
614 -- in which they're used doesn't cause problems on a Win32 platform though.)
616 asyncRead :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
617 asyncRead (I# fd) (I# isSock) (I# len) (Ptr buf) =
618 IO $ \s -> case asyncRead# fd isSock len buf s of
619 (# s, len#, err# #) -> (# s, (I# len#, I# err#) #)
621 asyncWrite :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
622 asyncWrite (I# fd) (I# isSock) (I# len) (Ptr buf) =
623 IO $ \s -> case asyncWrite# fd isSock len buf s of
624 (# s, len#, err# #) -> (# s, (I# len#, I# err#) #)
626 asyncDoProc :: FunPtr (Ptr a -> IO Int) -> Ptr a -> IO Int
627 asyncDoProc (FunPtr proc) (Ptr param) =
628 -- the 'length' value is ignored; simplifies implementation of
629 -- the async*# primops to have them all return the same result.
630 IO $ \s -> case asyncDoProc# proc param s of
631 (# s, len#, err# #) -> (# s, I# err# #)
633 -- to aid the use of these primops by the IO Handle implementation,
634 -- provide the following convenience funs:
636 -- this better be a pinned byte array!
637 asyncReadBA :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int,Int)
638 asyncReadBA fd isSock len off bufB =
639 asyncRead fd isSock len ((Ptr (byteArrayContents# (unsafeCoerce# bufB))) `plusPtr` off)
641 asyncWriteBA :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int,Int)
642 asyncWriteBA fd isSock len off bufB =
643 asyncWrite fd isSock len ((Ptr (byteArrayContents# (unsafeCoerce# bufB))) `plusPtr` off)
647 -- -----------------------------------------------------------------------------
650 -- | Block the current thread until data is available to read on the
651 -- given file descriptor (GHC only).
652 threadWaitRead :: Fd -> IO ()
654 #ifndef mingw32_HOST_OS
655 | threaded = waitForReadEvent fd
657 | otherwise = IO $ \s ->
658 case fromIntegral fd of { I# fd# ->
659 case waitRead# fd# s of { s -> (# s, () #)
662 -- | Block the current thread until data can be written to the
663 -- given file descriptor (GHC only).
664 threadWaitWrite :: Fd -> IO ()
666 #ifndef mingw32_HOST_OS
667 | threaded = waitForWriteEvent fd
669 | otherwise = IO $ \s ->
670 case fromIntegral fd of { I# fd# ->
671 case waitWrite# fd# s of { s -> (# s, () #)
674 -- | Suspends the current thread for a given number of microseconds
677 -- There is no guarantee that the thread will be rescheduled promptly
678 -- when the delay has expired, but the thread will never continue to
679 -- run /earlier/ than specified.
681 threadDelay :: Int -> IO ()
683 | threaded = waitForDelayEvent time
684 | otherwise = IO $ \s ->
685 case fromIntegral time of { I# time# ->
686 case delay# time# s of { s -> (# s, () #)
690 -- | Set the value of returned TVar to True after a given number of
691 -- microseconds. The caveats associated with threadDelay also apply.
693 registerDelay :: Int -> IO (TVar Bool)
695 | threaded = waitForDelayEventSTM usecs
696 | otherwise = error "registerDelay: requires -threaded"
698 foreign import ccall unsafe "rtsSupportsBoundThreads" threaded :: Bool
700 waitForDelayEvent :: Int -> IO ()
701 waitForDelayEvent usecs = do
703 target <- calculateTarget usecs
704 atomicModifyIORef pendingDelays (\xs -> (Delay target m : xs, ()))
708 -- Delays for use in STM
709 waitForDelayEventSTM :: Int -> IO (TVar Bool)
710 waitForDelayEventSTM usecs = do
711 t <- atomically $ newTVar False
712 target <- calculateTarget usecs
713 atomicModifyIORef pendingDelays (\xs -> (DelaySTM target t : xs, ()))
717 calculateTarget :: Int -> IO USecs
718 calculateTarget usecs = do
720 return $ now + (fromIntegral usecs)
723 -- ----------------------------------------------------------------------------
724 -- Threaded RTS implementation of threadWaitRead, threadWaitWrite, threadDelay
726 -- In the threaded RTS, we employ a single IO Manager thread to wait
727 -- for all outstanding IO requests (threadWaitRead,threadWaitWrite)
728 -- and delays (threadDelay).
730 -- We can do this because in the threaded RTS the IO Manager can make
731 -- a non-blocking call to select(), so we don't have to do select() in
732 -- the scheduler as we have to in the non-threaded RTS. We get performance
733 -- benefits from doing it this way, because we only have to restart the select()
734 -- when a new request arrives, rather than doing one select() each time
735 -- around the scheduler loop. Furthermore, the scheduler can be simplified
736 -- by not having to check for completed IO requests.
738 -- Issues, possible problems:
740 -- - we might want bound threads to just do the blocking
741 -- operation rather than communicating with the IO manager
742 -- thread. This would prevent simgle-threaded programs which do
743 -- IO from requiring multiple OS threads. However, it would also
744 -- prevent bound threads waiting on IO from being killed or sent
747 -- - Apprently exec() doesn't work on Linux in a multithreaded program.
748 -- I couldn't repeat this.
750 -- - How do we handle signal delivery in the multithreaded RTS?
752 -- - forkProcess will kill the IO manager thread. Let's just
753 -- hope we don't need to do any blocking IO between fork & exec.
755 #ifndef mingw32_HOST_OS
757 = Read {-# UNPACK #-} !Fd {-# UNPACK #-} !(MVar ())
758 | Write {-# UNPACK #-} !Fd {-# UNPACK #-} !(MVar ())
762 = Delay {-# UNPACK #-} !USecs {-# UNPACK #-} !(MVar ())
763 | DelaySTM {-# UNPACK #-} !USecs {-# UNPACK #-} !(TVar Bool)
765 #ifndef mingw32_HOST_OS
766 pendingEvents :: IORef [IOReq]
768 pendingDelays :: IORef [DelayReq]
769 -- could use a strict list or array here
770 {-# NOINLINE pendingEvents #-}
771 {-# NOINLINE pendingDelays #-}
772 (pendingEvents,pendingDelays) = unsafePerformIO $ do
777 -- the first time we schedule an IO request, the service thread
778 -- will be created (cool, huh?)
780 ensureIOManagerIsRunning :: IO ()
781 ensureIOManagerIsRunning
782 | threaded = seq pendingEvents $ return ()
783 | otherwise = return ()
785 insertDelay :: DelayReq -> [DelayReq] -> [DelayReq]
786 insertDelay d [] = [d]
787 insertDelay d1 ds@(d2 : rest)
788 | delayTime d1 <= delayTime d2 = d1 : ds
789 | otherwise = d2 : insertDelay d1 rest
791 delayTime :: DelayReq -> USecs
792 delayTime (Delay t _) = t
793 delayTime (DelaySTM t _) = t
797 -- XXX: move into GHC.IOBase from Data.IORef?
798 atomicModifyIORef :: IORef a -> (a -> (a,b)) -> IO b
799 atomicModifyIORef (IORef (STRef r#)) f = IO $ \s -> atomicModifyMutVar# r# f s
801 foreign import ccall unsafe "getUSecOfDay"
802 getUSecOfDay :: IO USecs
804 prodding :: IORef Bool
805 {-# NOINLINE prodding #-}
806 prodding = unsafePerformIO (newIORef False)
808 prodServiceThread :: IO ()
809 prodServiceThread = do
810 was_set <- atomicModifyIORef prodding (\a -> (True,a))
811 if (not (was_set)) then wakeupIOManager else return ()
813 #ifdef mingw32_HOST_OS
814 -- ----------------------------------------------------------------------------
815 -- Windows IO manager thread
817 startIOManagerThread :: IO ()
818 startIOManagerThread = do
819 wakeup <- c_getIOManagerEvent
820 forkIO $ service_loop wakeup []
823 service_loop :: HANDLE -- read end of pipe
824 -> [DelayReq] -- current delay requests
827 service_loop wakeup old_delays = do
828 -- pick up new delay requests
829 new_delays <- atomicModifyIORef pendingDelays (\a -> ([],a))
830 let delays = foldr insertDelay old_delays new_delays
833 (delays', timeout) <- getDelay now delays
835 r <- c_WaitForSingleObject wakeup timeout
837 0xffffffff -> do c_maperrno; throwErrno "service_loop"
839 r <- c_readIOManagerEvent
842 _ | r == io_MANAGER_WAKEUP -> return False
843 _ | r == io_MANAGER_DIE -> return True
844 0 -> return False -- spurious wakeup
845 r -> do start_console_handler (r `shiftR` 1); return False
848 else service_cont wakeup delays'
850 _other -> service_cont wakeup delays' -- probably timeout
852 service_cont wakeup delays = do
853 atomicModifyIORef prodding (\_ -> (False,False))
854 service_loop wakeup delays
856 -- must agree with rts/win32/ThrIOManager.c
857 io_MANAGER_WAKEUP = 0xffffffff :: Word32
858 io_MANAGER_DIE = 0xfffffffe :: Word32
864 -- these are sent to Services only.
867 deriving (Eq, Ord, Enum, Show, Read, Typeable)
869 start_console_handler :: Word32 -> IO ()
870 start_console_handler r =
871 case toWin32ConsoleEvent r of
872 Just x -> withMVar win32ConsoleHandler $ \handler -> do
877 toWin32ConsoleEvent ev =
879 0 {- CTRL_C_EVENT-} -> Just ControlC
880 1 {- CTRL_BREAK_EVENT-} -> Just Break
881 2 {- CTRL_CLOSE_EVENT-} -> Just Close
882 5 {- CTRL_LOGOFF_EVENT-} -> Just Logoff
883 6 {- CTRL_SHUTDOWN_EVENT-} -> Just Shutdown
886 win32ConsoleHandler :: MVar (ConsoleEvent -> IO ())
887 win32ConsoleHandler = unsafePerformIO (newMVar (error "win32ConsoleHandler"))
889 stick :: IORef HANDLE
890 {-# NOINLINE stick #-}
891 stick = unsafePerformIO (newIORef nullPtr)
894 hdl <- readIORef stick
895 c_sendIOManagerEvent io_MANAGER_WAKEUP
897 -- Walk the queue of pending delays, waking up any that have passed
898 -- and return the smallest delay to wait for. The queue of pending
899 -- delays is kept ordered.
900 getDelay :: USecs -> [DelayReq] -> IO ([DelayReq], DWORD)
901 getDelay now [] = return ([], iNFINITE)
902 getDelay now all@(d : rest)
904 Delay time m | now >= time -> do
907 DelaySTM time t | now >= time -> do
908 atomically $ writeTVar t True
911 -- delay is in millisecs for WaitForSingleObject
912 let micro_seconds = delayTime d - now
913 milli_seconds = (micro_seconds + 999) `div` 1000
914 in return (all, fromIntegral milli_seconds)
916 -- ToDo: this just duplicates part of System.Win32.Types, which isn't
917 -- available yet. We should move some Win32 functionality down here,
918 -- maybe as part of the grand reorganisation of the base package...
922 iNFINITE = 0xFFFFFFFF :: DWORD -- urgh
924 foreign import ccall unsafe "getIOManagerEvent" -- in the RTS (ThrIOManager.c)
925 c_getIOManagerEvent :: IO HANDLE
927 foreign import ccall unsafe "readIOManagerEvent" -- in the RTS (ThrIOManager.c)
928 c_readIOManagerEvent :: IO Word32
930 foreign import ccall unsafe "sendIOManagerEvent" -- in the RTS (ThrIOManager.c)
931 c_sendIOManagerEvent :: Word32 -> IO ()
933 foreign import ccall unsafe "maperrno" -- in Win32Utils.c
936 foreign import stdcall "WaitForSingleObject"
937 c_WaitForSingleObject :: HANDLE -> DWORD -> IO DWORD
940 -- ----------------------------------------------------------------------------
941 -- Unix IO manager thread, using select()
943 startIOManagerThread :: IO ()
944 startIOManagerThread = do
945 allocaArray 2 $ \fds -> do
946 throwErrnoIfMinus1 "startIOManagerThread" (c_pipe fds)
947 rd_end <- peekElemOff fds 0
948 wr_end <- peekElemOff fds 1
949 writeIORef stick (fromIntegral wr_end)
950 c_setIOManagerPipe wr_end
952 allocaBytes sizeofFdSet $ \readfds -> do
953 allocaBytes sizeofFdSet $ \writefds -> do
954 allocaBytes sizeofTimeVal $ \timeval -> do
955 service_loop (fromIntegral rd_end) readfds writefds timeval [] []
959 :: Fd -- listen to this for wakeup calls
966 service_loop wakeup readfds writefds ptimeval old_reqs old_delays = do
968 -- pick up new IO requests
969 new_reqs <- atomicModifyIORef pendingEvents (\a -> ([],a))
970 let reqs = new_reqs ++ old_reqs
972 -- pick up new delay requests
973 new_delays <- atomicModifyIORef pendingDelays (\a -> ([],a))
974 let delays = foldr insertDelay old_delays new_delays
976 -- build the FDSets for select()
980 maxfd <- buildFdSets 0 readfds writefds reqs
982 -- perform the select()
983 let do_select delays = do
984 -- check the current time and wake up any thread in
985 -- threadDelay whose timeout has expired. Also find the
986 -- timeout value for the select() call.
988 (delays', timeout) <- getDelay now ptimeval delays
990 res <- c_select (fromIntegral ((max wakeup maxfd)+1)) readfds writefds
996 _ | err == eINTR -> do_select delays'
997 -- EINTR: just redo the select()
998 _ | err == eBADF -> return (True, delays)
999 -- EBADF: one of the file descriptors is closed or bad,
1000 -- we don't know which one, so wake everyone up.
1001 _ | otherwise -> throwErrno "select"
1002 -- otherwise (ENOMEM or EINVAL) something has gone
1003 -- wrong; report the error.
1005 return (False,delays')
1007 (wakeup_all,delays') <- do_select delays
1010 if wakeup_all then return False
1012 b <- fdIsSet wakeup readfds
1015 else alloca $ \p -> do
1016 c_read (fromIntegral wakeup) p 1; return ()
1019 _ | s == io_MANAGER_WAKEUP -> return False
1020 _ | s == io_MANAGER_DIE -> return True
1021 _ -> withMVar signalHandlerLock $ \_ -> do
1022 handler_tbl <- peek handlers
1023 sp <- peekElemOff handler_tbl (fromIntegral s)
1024 io <- deRefStablePtr sp
1028 if exit then return () else do
1030 atomicModifyIORef prodding (\_ -> (False,False))
1032 reqs' <- if wakeup_all then do wakeupAll reqs; return []
1033 else completeRequests reqs readfds writefds []
1035 service_loop wakeup readfds writefds ptimeval reqs' delays'
1037 io_MANAGER_WAKEUP = 0xff :: CChar
1038 io_MANAGER_DIE = 0xfe :: CChar
1041 {-# NOINLINE stick #-}
1042 stick = unsafePerformIO (newIORef 0)
1044 wakeupIOManager :: IO ()
1045 wakeupIOManager = do
1046 fd <- readIORef stick
1047 with io_MANAGER_WAKEUP $ \pbuf -> do
1048 c_write (fromIntegral fd) pbuf 1; return ()
1050 -- Lock used to protect concurrent access to signal_handlers. Symptom of
1051 -- this race condition is #1922, although that bug was on Windows a similar
1052 -- bug also exists on Unix.
1053 signalHandlerLock :: MVar ()
1054 signalHandlerLock = unsafePerformIO (newMVar ())
1056 foreign import ccall "&signal_handlers" handlers :: Ptr (Ptr (StablePtr (IO ())))
1058 foreign import ccall "setIOManagerPipe"
1059 c_setIOManagerPipe :: CInt -> IO ()
1061 -- -----------------------------------------------------------------------------
1064 buildFdSets maxfd readfds writefds [] = return maxfd
1065 buildFdSets maxfd readfds writefds (Read fd m : reqs)
1066 | fd >= fD_SETSIZE = error "buildFdSets: file descriptor out of range"
1069 buildFdSets (max maxfd fd) readfds writefds reqs
1070 buildFdSets maxfd readfds writefds (Write fd m : reqs)
1071 | fd >= fD_SETSIZE = error "buildFdSets: file descriptor out of range"
1074 buildFdSets (max maxfd fd) readfds writefds reqs
1076 completeRequests [] _ _ reqs' = return reqs'
1077 completeRequests (Read fd m : reqs) readfds writefds reqs' = do
1078 b <- fdIsSet fd readfds
1080 then do putMVar m (); completeRequests reqs readfds writefds reqs'
1081 else completeRequests reqs readfds writefds (Read fd m : reqs')
1082 completeRequests (Write fd m : reqs) readfds writefds reqs' = do
1083 b <- fdIsSet fd writefds
1085 then do putMVar m (); completeRequests reqs readfds writefds reqs'
1086 else completeRequests reqs readfds writefds (Write fd m : reqs')
1088 wakeupAll [] = return ()
1089 wakeupAll (Read fd m : reqs) = do putMVar m (); wakeupAll reqs
1090 wakeupAll (Write fd m : reqs) = do putMVar m (); wakeupAll reqs
1092 waitForReadEvent :: Fd -> IO ()
1093 waitForReadEvent fd = do
1095 atomicModifyIORef pendingEvents (\xs -> (Read fd m : xs, ()))
1099 waitForWriteEvent :: Fd -> IO ()
1100 waitForWriteEvent fd = do
1102 atomicModifyIORef pendingEvents (\xs -> (Write fd m : xs, ()))
1106 -- -----------------------------------------------------------------------------
1109 -- Walk the queue of pending delays, waking up any that have passed
1110 -- and return the smallest delay to wait for. The queue of pending
1111 -- delays is kept ordered.
1112 getDelay :: USecs -> Ptr CTimeVal -> [DelayReq] -> IO ([DelayReq], Ptr CTimeVal)
1113 getDelay now ptimeval [] = return ([],nullPtr)
1114 getDelay now ptimeval all@(d : rest)
1116 Delay time m | now >= time -> do
1118 getDelay now ptimeval rest
1119 DelaySTM time t | now >= time -> do
1120 atomically $ writeTVar t True
1121 getDelay now ptimeval rest
1123 setTimevalTicks ptimeval (delayTime d - now)
1124 return (all,ptimeval)
1126 newtype CTimeVal = CTimeVal ()
1128 foreign import ccall unsafe "sizeofTimeVal"
1129 sizeofTimeVal :: Int
1131 foreign import ccall unsafe "setTimevalTicks"
1132 setTimevalTicks :: Ptr CTimeVal -> USecs -> IO ()
1135 On Win32 we're going to have a single Pipe, and a
1136 waitForSingleObject with the delay time. For signals, we send a
1137 byte down the pipe just like on Unix.
1140 -- ----------------------------------------------------------------------------
1141 -- select() interface
1143 -- ToDo: move to System.Posix.Internals?
1145 newtype CFdSet = CFdSet ()
1147 foreign import ccall safe "select"
1148 c_select :: CInt -> Ptr CFdSet -> Ptr CFdSet -> Ptr CFdSet -> Ptr CTimeVal
1151 foreign import ccall unsafe "hsFD_SETSIZE"
1152 c_fD_SETSIZE :: CInt
1155 fD_SETSIZE = fromIntegral c_fD_SETSIZE
1157 foreign import ccall unsafe "hsFD_CLR"
1158 c_fdClr :: CInt -> Ptr CFdSet -> IO ()
1160 fdClr :: Fd -> Ptr CFdSet -> IO ()
1161 fdClr (Fd fd) fdset = c_fdClr fd fdset
1163 foreign import ccall unsafe "hsFD_ISSET"
1164 c_fdIsSet :: CInt -> Ptr CFdSet -> IO CInt
1166 fdIsSet :: Fd -> Ptr CFdSet -> IO CInt
1167 fdIsSet (Fd fd) fdset = c_fdIsSet fd fdset
1169 foreign import ccall unsafe "hsFD_SET"
1170 c_fdSet :: CInt -> Ptr CFdSet -> IO ()
1172 fdSet :: Fd -> Ptr CFdSet -> IO ()
1173 fdSet (Fd fd) fdset = c_fdSet fd fdset
1175 foreign import ccall unsafe "hsFD_ZERO"
1176 fdZero :: Ptr CFdSet -> IO ()
1178 foreign import ccall unsafe "sizeof_fd_set"