2 {-# OPTIONS_GHC -fno-implicit-prelude #-}
3 -----------------------------------------------------------------------------
6 -- Copyright : (c) The University of Glasgow, 1994-2002
7 -- License : see libraries/base/LICENSE
9 -- Maintainer : cvs-ghc@haskell.org
10 -- Stability : internal
11 -- Portability : non-portable (GHC extensions)
13 -- Basic concurrency stuff.
15 -----------------------------------------------------------------------------
17 -- No: #hide, because bits of this module are exposed by the stm package.
18 -- However, we don't want this module to be the home location for the
19 -- bits it exports, we'd rather have Control.Concurrent and the other
20 -- higher level modules be the home. Hence:
28 -- * Forking and suchlike
29 , forkIO -- :: IO a -> IO ThreadId
30 , forkOnIO -- :: Int -> IO a -> IO ThreadId
31 , numCapabilities -- :: Int
32 , childHandler -- :: Exception -> IO ()
33 , myThreadId -- :: IO ThreadId
34 , killThread -- :: ThreadId -> IO ()
35 , throwTo -- :: ThreadId -> Exception -> IO ()
36 , par -- :: a -> b -> b
37 , pseq -- :: a -> b -> b
39 , labelThread -- :: ThreadId -> String -> IO ()
42 , threadDelay -- :: Int -> IO ()
43 , registerDelay -- :: Int -> IO (TVar Bool)
44 , threadWaitRead -- :: Int -> IO ()
45 , threadWaitWrite -- :: Int -> IO ()
49 , newMVar -- :: a -> IO (MVar a)
50 , newEmptyMVar -- :: IO (MVar a)
51 , takeMVar -- :: MVar a -> IO a
52 , putMVar -- :: MVar a -> a -> IO ()
53 , tryTakeMVar -- :: MVar a -> IO (Maybe a)
54 , tryPutMVar -- :: MVar a -> a -> IO Bool
55 , isEmptyMVar -- :: MVar a -> IO Bool
56 , addMVarFinalizer -- :: MVar a -> IO () -> IO ()
60 , atomically -- :: STM a -> IO a
62 , orElse -- :: STM a -> STM a -> STM a
63 , catchSTM -- :: STM a -> (Exception -> STM a) -> STM a
64 , alwaysSucceeds -- :: STM a -> STM ()
65 , always -- :: STM Bool -> STM ()
67 , newTVar -- :: a -> STM (TVar a)
68 , newTVarIO -- :: a -> STM (TVar a)
69 , readTVar -- :: TVar a -> STM a
70 , writeTVar -- :: a -> TVar a -> STM ()
71 , unsafeIOToSTM -- :: IO a -> STM a
74 #ifdef mingw32_HOST_OS
75 , asyncRead -- :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
76 , asyncWrite -- :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
77 , asyncDoProc -- :: FunPtr (Ptr a -> IO Int) -> Ptr a -> IO Int
79 , asyncReadBA -- :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int, Int)
80 , asyncWriteBA -- :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int, Int)
83 , ensureIOManagerIsRunning
86 import System.Posix.Types
87 #ifndef mingw32_HOST_OS
88 import System.Posix.Internals
94 import {-# SOURCE #-} GHC.TopHandler ( reportError, reportStackOverflow )
101 import GHC.Num ( Num(..) )
102 import GHC.Real ( fromIntegral, div )
103 #ifndef mingw32_HOST_OS
104 import GHC.Base ( Int(..) )
106 import GHC.Exception ( catchException, Exception(..), AsyncException(..) )
107 import GHC.Pack ( packCString# )
108 import GHC.Ptr ( Ptr(..), plusPtr, FunPtr(..) )
110 import GHC.Show ( Show(..), showString )
113 infixr 0 `par`, `pseq`
116 %************************************************************************
118 \subsection{@ThreadId@, @par@, and @fork@}
120 %************************************************************************
123 data ThreadId = ThreadId ThreadId# deriving( Typeable )
124 -- ToDo: data ThreadId = ThreadId (Weak ThreadId#)
125 -- But since ThreadId# is unlifted, the Weak type must use open
128 A 'ThreadId' is an abstract type representing a handle to a thread.
129 'ThreadId' is an instance of 'Eq', 'Ord' and 'Show', where
130 the 'Ord' instance implements an arbitrary total ordering over
131 'ThreadId's. The 'Show' instance lets you convert an arbitrary-valued
132 'ThreadId' to string form; showing a 'ThreadId' value is occasionally
133 useful when debugging or diagnosing the behaviour of a concurrent
136 /Note/: in GHC, if you have a 'ThreadId', you essentially have
137 a pointer to the thread itself. This means the thread itself can\'t be
138 garbage collected until you drop the 'ThreadId'.
139 This misfeature will hopefully be corrected at a later date.
141 /Note/: Hugs does not provide any operations on other threads;
142 it defines 'ThreadId' as a synonym for ().
145 instance Show ThreadId where
147 showString "ThreadId " .
148 showsPrec d (getThreadId (id2TSO t))
150 foreign import ccall unsafe "rts_getThreadId" getThreadId :: ThreadId# -> CInt
152 id2TSO :: ThreadId -> ThreadId#
153 id2TSO (ThreadId t) = t
155 foreign import ccall unsafe "cmp_thread" cmp_thread :: ThreadId# -> ThreadId# -> CInt
158 cmpThread :: ThreadId -> ThreadId -> Ordering
160 case cmp_thread (id2TSO t1) (id2TSO t2) of
165 instance Eq ThreadId where
167 case t1 `cmpThread` t2 of
171 instance Ord ThreadId where
175 This sparks off a new thread to run the 'IO' computation passed as the
176 first argument, and returns the 'ThreadId' of the newly created
179 The new thread will be a lightweight thread; if you want to use a foreign
180 library that uses thread-local storage, use 'forkOS' instead.
182 forkIO :: IO () -> IO ThreadId
183 forkIO action = IO $ \ s ->
184 case (fork# action_plus s) of (# s1, id #) -> (# s1, ThreadId id #)
186 action_plus = catchException action childHandler
188 forkOnIO :: Int -> IO () -> IO ThreadId
189 forkOnIO (I# cpu) action = IO $ \ s ->
190 case (forkOn# cpu action_plus s) of (# s1, id #) -> (# s1, ThreadId id #)
192 action_plus = catchException action childHandler
194 -- | the value passed to the @+RTS -N@ flag. This is the number of
195 -- Haskell threads that can run truly simultaneously at any given
196 -- time, and is typically set to the number of physical CPU cores on
198 numCapabilities :: Int
199 numCapabilities = unsafePerformIO $ do
200 n <- peek n_capabilities
201 return (fromIntegral n)
203 foreign import ccall "&n_capabilities" n_capabilities :: Ptr CInt
205 childHandler :: Exception -> IO ()
206 childHandler err = catchException (real_handler err) childHandler
208 real_handler :: Exception -> IO ()
211 -- ignore thread GC and killThread exceptions:
212 BlockedOnDeadMVar -> return ()
213 BlockedIndefinitely -> return ()
214 AsyncException ThreadKilled -> return ()
216 -- report all others:
217 AsyncException StackOverflow -> reportStackOverflow
218 other -> reportError other
220 {- | 'killThread' terminates the given thread (GHC only).
221 Any work already done by the thread isn\'t
222 lost: the computation is suspended until required by another thread.
223 The memory used by the thread will be garbage collected if it isn\'t
224 referenced from anywhere. The 'killThread' function is defined in
227 > killThread tid = throwTo tid (AsyncException ThreadKilled)
230 killThread :: ThreadId -> IO ()
231 killThread tid = throwTo tid (AsyncException ThreadKilled)
233 {- | 'throwTo' raises an arbitrary exception in the target thread (GHC only).
235 'throwTo' does not return until the exception has been raised in the
237 The calling thread can thus be certain that the target
238 thread has received the exception. This is a useful property to know
239 when dealing with race conditions: eg. if there are two threads that
240 can kill each other, it is guaranteed that only one of the threads
241 will get to kill the other.
243 If the target thread is currently making a foreign call, then the
244 exception will not be raised (and hence 'throwTo' will not return)
245 until the call has completed. This is the case regardless of whether
246 the call is inside a 'block' or not.
248 Important note: the behaviour of 'throwTo' differs from that described in
249 the paper "Asynchronous exceptions in Haskell"
250 (<http://research.microsoft.com/~simonpj/Papers/asynch-exns.htm>).
251 In the paper, 'throwTo' is non-blocking; but the library implementation adopts
252 a more synchronous design in which 'throwTo' does not return until the exception
253 is received by the target thread. The trade-off is discussed in Section 8 of the paper.
254 Like any blocking operation, 'throwTo' is therefore interruptible (see Section 4.3 of
257 There is currently no guarantee that the exception delivered by 'throwTo' will be
258 delivered at the first possible opportunity. In particular, if a thread may
259 unblock and then re-block exceptions (using 'unblock' and 'block') without receiving
260 a pending 'throwTo'. This is arguably undesirable behaviour.
263 throwTo :: ThreadId -> Exception -> IO ()
264 throwTo (ThreadId id) ex = IO $ \ s ->
265 case (killThread# id ex s) of s1 -> (# s1, () #)
267 -- | Returns the 'ThreadId' of the calling thread (GHC only).
268 myThreadId :: IO ThreadId
269 myThreadId = IO $ \s ->
270 case (myThreadId# s) of (# s1, id #) -> (# s1, ThreadId id #)
273 -- |The 'yield' action allows (forces, in a co-operative multitasking
274 -- implementation) a context-switch to any other currently runnable
275 -- threads (if any), and is occasionally useful when implementing
276 -- concurrency abstractions.
279 case (yield# s) of s1 -> (# s1, () #)
281 {- | 'labelThread' stores a string as identifier for this thread if
282 you built a RTS with debugging support. This identifier will be used in
283 the debugging output to make distinction of different threads easier
284 (otherwise you only have the thread state object\'s address in the heap).
286 Other applications like the graphical Concurrent Haskell Debugger
287 (<http://www.informatik.uni-kiel.de/~fhu/chd/>) may choose to overload
288 'labelThread' for their purposes as well.
291 labelThread :: ThreadId -> String -> IO ()
292 labelThread (ThreadId t) str = IO $ \ s ->
293 let ps = packCString# str
294 adr = byteArrayContents# ps in
295 case (labelThread# t adr s) of s1 -> (# s1, () #)
297 -- Nota Bene: 'pseq' used to be 'seq'
298 -- but 'seq' is now defined in PrelGHC
300 -- "pseq" is defined a bit weirdly (see below)
302 -- The reason for the strange "lazy" call is that
303 -- it fools the compiler into thinking that pseq and par are non-strict in
304 -- their second argument (even if it inlines pseq at the call site).
305 -- If it thinks pseq is strict in "y", then it often evaluates
306 -- "y" before "x", which is totally wrong.
310 pseq x y = x `seq` lazy y
314 par x y = case (par# x) of { _ -> lazy y }
318 %************************************************************************
320 \subsection[stm]{Transactional heap operations}
322 %************************************************************************
324 TVars are shared memory locations which support atomic memory
328 -- |A monad supporting atomic memory transactions.
329 newtype STM a = STM (State# RealWorld -> (# State# RealWorld, a #))
331 unSTM :: STM a -> (State# RealWorld -> (# State# RealWorld, a #))
334 INSTANCE_TYPEABLE1(STM,stmTc,"STM")
336 instance Functor STM where
337 fmap f x = x >>= (return . f)
339 instance Monad STM where
340 {-# INLINE return #-}
344 return x = returnSTM x
345 m >>= k = bindSTM m k
347 bindSTM :: STM a -> (a -> STM b) -> STM b
348 bindSTM (STM m) k = STM ( \s ->
350 (# new_s, a #) -> unSTM (k a) new_s
353 thenSTM :: STM a -> STM b -> STM b
354 thenSTM (STM m) k = STM ( \s ->
356 (# new_s, a #) -> unSTM k new_s
359 returnSTM :: a -> STM a
360 returnSTM x = STM (\s -> (# s, x #))
362 -- | Unsafely performs IO in the STM monad.
363 unsafeIOToSTM :: IO a -> STM a
364 unsafeIOToSTM (IO m) = STM m
366 -- |Perform a series of STM actions atomically.
368 -- You cannot use 'atomically' inside an 'unsafePerformIO' or 'unsafeInterleaveIO'.
369 -- Any attempt to do so will result in a runtime error. (Reason: allowing
370 -- this would effectively allow a transaction inside a transaction, depending
371 -- on exactly when the thunk is evaluated.)
373 -- However, see 'newTVarIO', which can be called inside 'unsafePerformIO',
374 -- and which allows top-level TVars to be allocated.
376 atomically :: STM a -> IO a
377 atomically (STM m) = IO (\s -> (atomically# m) s )
379 -- |Retry execution of the current memory transaction because it has seen
380 -- values in TVars which mean that it should not continue (e.g. the TVars
381 -- represent a shared buffer that is now empty). The implementation may
382 -- block the thread until one of the TVars that it has read from has been
383 -- udpated. (GHC only)
385 retry = STM $ \s# -> retry# s#
387 -- |Compose two alternative STM actions (GHC only). If the first action
388 -- completes without retrying then it forms the result of the orElse.
389 -- Otherwise, if the first action retries, then the second action is
390 -- tried in its place. If both actions retry then the orElse as a
392 orElse :: STM a -> STM a -> STM a
393 orElse (STM m) e = STM $ \s -> catchRetry# m (unSTM e) s
395 -- |Exception handling within STM actions.
396 catchSTM :: STM a -> (Exception -> STM a) -> STM a
397 catchSTM (STM m) k = STM $ \s -> catchSTM# m (\ex -> unSTM (k ex)) s
399 -- | Low-level primitive on which always and alwaysSucceeds are built.
400 -- checkInv differs form these in that (i) the invariant is not
401 -- checked when checkInv is called, only at the end of this and
402 -- subsequent transcations, (ii) the invariant failure is indicated
403 -- by raising an exception.
404 checkInv :: STM a -> STM ()
405 checkInv (STM m) = STM (\s -> (check# m) s)
407 -- | alwaysSucceeds adds a new invariant that must be true when passed
408 -- to alwaysSucceeds, at the end of the current transaction, and at
409 -- the end of every subsequent transaction. If it fails at any
410 -- of those points then the transaction violating it is aborted
411 -- and the exception raised by the invariant is propagated.
412 alwaysSucceeds :: STM a -> STM ()
413 alwaysSucceeds i = do ( do i ; retry ) `orElse` ( return () )
416 -- | always is a variant of alwaysSucceeds in which the invariant is
417 -- expressed as an STM Bool action that must return True. Returning
418 -- False or raising an exception are both treated as invariant failures.
419 always :: STM Bool -> STM ()
420 always i = alwaysSucceeds ( do v <- i
421 if (v) then return () else ( error "Transacional invariant violation" ) )
423 -- |Shared memory locations that support atomic memory transactions.
424 data TVar a = TVar (TVar# RealWorld a)
426 INSTANCE_TYPEABLE1(TVar,tvarTc,"TVar")
428 instance Eq (TVar a) where
429 (TVar tvar1#) == (TVar tvar2#) = sameTVar# tvar1# tvar2#
431 -- |Create a new TVar holding a value supplied
432 newTVar :: a -> STM (TVar a)
433 newTVar val = STM $ \s1# ->
434 case newTVar# val s1# of
435 (# s2#, tvar# #) -> (# s2#, TVar tvar# #)
437 -- |@IO@ version of 'newTVar'. This is useful for creating top-level
438 -- 'TVar's using 'System.IO.Unsafe.unsafePerformIO', because using
439 -- 'atomically' inside 'System.IO.Unsafe.unsafePerformIO' isn't
441 newTVarIO :: a -> IO (TVar a)
442 newTVarIO val = IO $ \s1# ->
443 case newTVar# val s1# of
444 (# s2#, tvar# #) -> (# s2#, TVar tvar# #)
446 -- |Return the current value stored in a TVar
447 readTVar :: TVar a -> STM a
448 readTVar (TVar tvar#) = STM $ \s# -> readTVar# tvar# s#
450 -- |Write the supplied value into a TVar
451 writeTVar :: TVar a -> a -> STM ()
452 writeTVar (TVar tvar#) val = STM $ \s1# ->
453 case writeTVar# tvar# val s1# of
458 %************************************************************************
460 \subsection[mvars]{M-Structures}
462 %************************************************************************
464 M-Vars are rendezvous points for concurrent threads. They begin
465 empty, and any attempt to read an empty M-Var blocks. When an M-Var
466 is written, a single blocked thread may be freed. Reading an M-Var
467 toggles its state from full back to empty. Therefore, any value
468 written to an M-Var may only be read once. Multiple reads and writes
469 are allowed, but there must be at least one read between any two
473 --Defined in IOBase to avoid cycle: data MVar a = MVar (SynchVar# RealWorld a)
475 -- |Create an 'MVar' which is initially empty.
476 newEmptyMVar :: IO (MVar a)
477 newEmptyMVar = IO $ \ s# ->
479 (# s2#, svar# #) -> (# s2#, MVar svar# #)
481 -- |Create an 'MVar' which contains the supplied value.
482 newMVar :: a -> IO (MVar a)
484 newEmptyMVar >>= \ mvar ->
485 putMVar mvar value >>
488 -- |Return the contents of the 'MVar'. If the 'MVar' is currently
489 -- empty, 'takeMVar' will wait until it is full. After a 'takeMVar',
490 -- the 'MVar' is left empty.
492 -- There are two further important properties of 'takeMVar':
494 -- * 'takeMVar' is single-wakeup. That is, if there are multiple
495 -- threads blocked in 'takeMVar', and the 'MVar' becomes full,
496 -- only one thread will be woken up. The runtime guarantees that
497 -- the woken thread completes its 'takeMVar' operation.
499 -- * When multiple threads are blocked on an 'MVar', they are
500 -- woken up in FIFO order. This is useful for providing
501 -- fairness properties of abstractions built using 'MVar's.
503 takeMVar :: MVar a -> IO a
504 takeMVar (MVar mvar#) = IO $ \ s# -> takeMVar# mvar# s#
506 -- |Put a value into an 'MVar'. If the 'MVar' is currently full,
507 -- 'putMVar' will wait until it becomes empty.
509 -- There are two further important properties of 'putMVar':
511 -- * 'putMVar' is single-wakeup. That is, if there are multiple
512 -- threads blocked in 'putMVar', and the 'MVar' becomes empty,
513 -- only one thread will be woken up. The runtime guarantees that
514 -- the woken thread completes its 'putMVar' operation.
516 -- * When multiple threads are blocked on an 'MVar', they are
517 -- woken up in FIFO order. This is useful for providing
518 -- fairness properties of abstractions built using 'MVar's.
520 putMVar :: MVar a -> a -> IO ()
521 putMVar (MVar mvar#) x = IO $ \ s# ->
522 case putMVar# mvar# x s# of
525 -- |A non-blocking version of 'takeMVar'. The 'tryTakeMVar' function
526 -- returns immediately, with 'Nothing' if the 'MVar' was empty, or
527 -- @'Just' a@ if the 'MVar' was full with contents @a@. After 'tryTakeMVar',
528 -- the 'MVar' is left empty.
529 tryTakeMVar :: MVar a -> IO (Maybe a)
530 tryTakeMVar (MVar m) = IO $ \ s ->
531 case tryTakeMVar# m s of
532 (# s, 0#, _ #) -> (# s, Nothing #) -- MVar is empty
533 (# s, _, a #) -> (# s, Just a #) -- MVar is full
535 -- |A non-blocking version of 'putMVar'. The 'tryPutMVar' function
536 -- attempts to put the value @a@ into the 'MVar', returning 'True' if
537 -- it was successful, or 'False' otherwise.
538 tryPutMVar :: MVar a -> a -> IO Bool
539 tryPutMVar (MVar mvar#) x = IO $ \ s# ->
540 case tryPutMVar# mvar# x s# of
541 (# s, 0# #) -> (# s, False #)
542 (# s, _ #) -> (# s, True #)
544 -- |Check whether a given 'MVar' is empty.
546 -- Notice that the boolean value returned is just a snapshot of
547 -- the state of the MVar. By the time you get to react on its result,
548 -- the MVar may have been filled (or emptied) - so be extremely
549 -- careful when using this operation. Use 'tryTakeMVar' instead if possible.
550 isEmptyMVar :: MVar a -> IO Bool
551 isEmptyMVar (MVar mv#) = IO $ \ s# ->
552 case isEmptyMVar# mv# s# of
553 (# s2#, flg #) -> (# s2#, not (flg ==# 0#) #)
555 -- |Add a finalizer to an 'MVar' (GHC only). See "Foreign.ForeignPtr" and
556 -- "System.Mem.Weak" for more about finalizers.
557 addMVarFinalizer :: MVar a -> IO () -> IO ()
558 addMVarFinalizer (MVar m) finalizer =
559 IO $ \s -> case mkWeak# m () finalizer s of { (# s1, w #) -> (# s1, () #) }
563 %************************************************************************
565 \subsection{Thread waiting}
567 %************************************************************************
570 #ifdef mingw32_HOST_OS
572 -- Note: threadDelay, threadWaitRead and threadWaitWrite aren't really functional
573 -- on Win32, but left in there because lib code (still) uses them (the manner
574 -- in which they're used doesn't cause problems on a Win32 platform though.)
576 asyncRead :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
577 asyncRead (I# fd) (I# isSock) (I# len) (Ptr buf) =
578 IO $ \s -> case asyncRead# fd isSock len buf s of
579 (# s, len#, err# #) -> (# s, (I# len#, I# err#) #)
581 asyncWrite :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
582 asyncWrite (I# fd) (I# isSock) (I# len) (Ptr buf) =
583 IO $ \s -> case asyncWrite# fd isSock len buf s of
584 (# s, len#, err# #) -> (# s, (I# len#, I# err#) #)
586 asyncDoProc :: FunPtr (Ptr a -> IO Int) -> Ptr a -> IO Int
587 asyncDoProc (FunPtr proc) (Ptr param) =
588 -- the 'length' value is ignored; simplifies implementation of
589 -- the async*# primops to have them all return the same result.
590 IO $ \s -> case asyncDoProc# proc param s of
591 (# s, len#, err# #) -> (# s, I# err# #)
593 -- to aid the use of these primops by the IO Handle implementation,
594 -- provide the following convenience funs:
596 -- this better be a pinned byte array!
597 asyncReadBA :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int,Int)
598 asyncReadBA fd isSock len off bufB =
599 asyncRead fd isSock len ((Ptr (byteArrayContents# (unsafeCoerce# bufB))) `plusPtr` off)
601 asyncWriteBA :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int,Int)
602 asyncWriteBA fd isSock len off bufB =
603 asyncWrite fd isSock len ((Ptr (byteArrayContents# (unsafeCoerce# bufB))) `plusPtr` off)
607 -- -----------------------------------------------------------------------------
610 -- | Block the current thread until data is available to read on the
611 -- given file descriptor (GHC only).
612 threadWaitRead :: Fd -> IO ()
614 #ifndef mingw32_HOST_OS
615 | threaded = waitForReadEvent fd
617 | otherwise = IO $ \s ->
618 case fromIntegral fd of { I# fd# ->
619 case waitRead# fd# s of { s -> (# s, () #)
622 -- | Block the current thread until data can be written to the
623 -- given file descriptor (GHC only).
624 threadWaitWrite :: Fd -> IO ()
626 #ifndef mingw32_HOST_OS
627 | threaded = waitForWriteEvent fd
629 | otherwise = IO $ \s ->
630 case fromIntegral fd of { I# fd# ->
631 case waitWrite# fd# s of { s -> (# s, () #)
634 -- | Suspends the current thread for a given number of microseconds
637 -- There is no guarantee that the thread will be rescheduled promptly
638 -- when the delay has expired, but the thread will never continue to
639 -- run /earlier/ than specified.
641 threadDelay :: Int -> IO ()
643 | threaded = waitForDelayEvent time
644 | otherwise = IO $ \s ->
645 case fromIntegral time of { I# time# ->
646 case delay# time# s of { s -> (# s, () #)
650 -- | Set the value of returned TVar to True after a given number of
651 -- microseconds. The caveats associated with threadDelay also apply.
653 registerDelay :: Int -> IO (TVar Bool)
655 | threaded = waitForDelayEventSTM usecs
656 | otherwise = error "registerDelay: requires -threaded"
658 foreign import ccall unsafe "rtsSupportsBoundThreads" threaded :: Bool
660 waitForDelayEvent :: Int -> IO ()
661 waitForDelayEvent usecs = do
663 target <- calculateTarget usecs
664 atomicModifyIORef pendingDelays (\xs -> (Delay target m : xs, ()))
668 -- Delays for use in STM
669 waitForDelayEventSTM :: Int -> IO (TVar Bool)
670 waitForDelayEventSTM usecs = do
671 t <- atomically $ newTVar False
672 target <- calculateTarget usecs
673 atomicModifyIORef pendingDelays (\xs -> (DelaySTM target t : xs, ()))
677 calculateTarget :: Int -> IO USecs
678 calculateTarget usecs = do
680 return $ now + (fromIntegral usecs)
683 -- ----------------------------------------------------------------------------
684 -- Threaded RTS implementation of threadWaitRead, threadWaitWrite, threadDelay
686 -- In the threaded RTS, we employ a single IO Manager thread to wait
687 -- for all outstanding IO requests (threadWaitRead,threadWaitWrite)
688 -- and delays (threadDelay).
690 -- We can do this because in the threaded RTS the IO Manager can make
691 -- a non-blocking call to select(), so we don't have to do select() in
692 -- the scheduler as we have to in the non-threaded RTS. We get performance
693 -- benefits from doing it this way, because we only have to restart the select()
694 -- when a new request arrives, rather than doing one select() each time
695 -- around the scheduler loop. Furthermore, the scheduler can be simplified
696 -- by not having to check for completed IO requests.
698 -- Issues, possible problems:
700 -- - we might want bound threads to just do the blocking
701 -- operation rather than communicating with the IO manager
702 -- thread. This would prevent simgle-threaded programs which do
703 -- IO from requiring multiple OS threads. However, it would also
704 -- prevent bound threads waiting on IO from being killed or sent
707 -- - Apprently exec() doesn't work on Linux in a multithreaded program.
708 -- I couldn't repeat this.
710 -- - How do we handle signal delivery in the multithreaded RTS?
712 -- - forkProcess will kill the IO manager thread. Let's just
713 -- hope we don't need to do any blocking IO between fork & exec.
715 #ifndef mingw32_HOST_OS
717 = Read {-# UNPACK #-} !Fd {-# UNPACK #-} !(MVar ())
718 | Write {-# UNPACK #-} !Fd {-# UNPACK #-} !(MVar ())
722 = Delay {-# UNPACK #-} !USecs {-# UNPACK #-} !(MVar ())
723 | DelaySTM {-# UNPACK #-} !USecs {-# UNPACK #-} !(TVar Bool)
725 #ifndef mingw32_HOST_OS
726 pendingEvents :: IORef [IOReq]
728 pendingDelays :: IORef [DelayReq]
729 -- could use a strict list or array here
730 {-# NOINLINE pendingEvents #-}
731 {-# NOINLINE pendingDelays #-}
732 (pendingEvents,pendingDelays) = unsafePerformIO $ do
737 -- the first time we schedule an IO request, the service thread
738 -- will be created (cool, huh?)
740 ensureIOManagerIsRunning :: IO ()
741 ensureIOManagerIsRunning
742 | threaded = seq pendingEvents $ return ()
743 | otherwise = return ()
745 insertDelay :: DelayReq -> [DelayReq] -> [DelayReq]
746 insertDelay d [] = [d]
747 insertDelay d1 ds@(d2 : rest)
748 | delayTime d1 <= delayTime d2 = d1 : ds
749 | otherwise = d2 : insertDelay d1 rest
751 delayTime :: DelayReq -> USecs
752 delayTime (Delay t _) = t
753 delayTime (DelaySTM t _) = t
757 -- XXX: move into GHC.IOBase from Data.IORef?
758 atomicModifyIORef :: IORef a -> (a -> (a,b)) -> IO b
759 atomicModifyIORef (IORef (STRef r#)) f = IO $ \s -> atomicModifyMutVar# r# f s
761 foreign import ccall unsafe "getUSecOfDay"
762 getUSecOfDay :: IO USecs
764 prodding :: IORef Bool
765 {-# NOINLINE prodding #-}
766 prodding = unsafePerformIO (newIORef False)
768 prodServiceThread :: IO ()
769 prodServiceThread = do
770 was_set <- atomicModifyIORef prodding (\a -> (True,a))
771 if (not (was_set)) then wakeupIOManager else return ()
773 #ifdef mingw32_HOST_OS
774 -- ----------------------------------------------------------------------------
775 -- Windows IO manager thread
777 startIOManagerThread :: IO ()
778 startIOManagerThread = do
779 wakeup <- c_getIOManagerEvent
780 forkIO $ service_loop wakeup []
783 service_loop :: HANDLE -- read end of pipe
784 -> [DelayReq] -- current delay requests
787 service_loop wakeup old_delays = do
788 -- pick up new delay requests
789 new_delays <- atomicModifyIORef pendingDelays (\a -> ([],a))
790 let delays = foldr insertDelay old_delays new_delays
793 (delays', timeout) <- getDelay now delays
795 r <- c_WaitForSingleObject wakeup timeout
797 0xffffffff -> do c_maperrno; throwErrno "service_loop"
799 r <- c_readIOManagerEvent
802 _ | r == io_MANAGER_WAKEUP -> return False
803 _ | r == io_MANAGER_DIE -> return True
804 0 -> return False -- spurious wakeup
805 r -> do start_console_handler (r `shiftR` 1); return False
808 else service_cont wakeup delays'
810 _other -> service_cont wakeup delays' -- probably timeout
812 service_cont wakeup delays = do
813 atomicModifyIORef prodding (\_ -> (False,False))
814 service_loop wakeup delays
816 -- must agree with rts/win32/ThrIOManager.c
817 io_MANAGER_WAKEUP = 0xffffffff :: Word32
818 io_MANAGER_DIE = 0xfffffffe :: Word32
820 start_console_handler :: Word32 -> IO ()
821 start_console_handler r = do
822 stableptr <- peek console_handler
823 forkIO $ do io <- deRefStablePtr stableptr; io (fromIntegral r)
826 foreign import ccall "&console_handler"
827 console_handler :: Ptr (StablePtr (CInt -> IO ()))
829 stick :: IORef HANDLE
830 {-# NOINLINE stick #-}
831 stick = unsafePerformIO (newIORef nullPtr)
834 hdl <- readIORef stick
835 c_sendIOManagerEvent io_MANAGER_WAKEUP
837 -- Walk the queue of pending delays, waking up any that have passed
838 -- and return the smallest delay to wait for. The queue of pending
839 -- delays is kept ordered.
840 getDelay :: USecs -> [DelayReq] -> IO ([DelayReq], DWORD)
841 getDelay now [] = return ([], iNFINITE)
842 getDelay now all@(d : rest)
844 Delay time m | now >= time -> do
847 DelaySTM time t | now >= time -> do
848 atomically $ writeTVar t True
851 -- delay is in millisecs for WaitForSingleObject
852 let micro_seconds = delayTime d - now
853 milli_seconds = (micro_seconds + 999) `div` 1000
854 in return (all, fromIntegral milli_seconds)
856 -- ToDo: this just duplicates part of System.Win32.Types, which isn't
857 -- available yet. We should move some Win32 functionality down here,
858 -- maybe as part of the grand reorganisation of the base package...
862 iNFINITE = 0xFFFFFFFF :: DWORD -- urgh
864 foreign import ccall unsafe "getIOManagerEvent" -- in the RTS (ThrIOManager.c)
865 c_getIOManagerEvent :: IO HANDLE
867 foreign import ccall unsafe "readIOManagerEvent" -- in the RTS (ThrIOManager.c)
868 c_readIOManagerEvent :: IO Word32
870 foreign import ccall unsafe "sendIOManagerEvent" -- in the RTS (ThrIOManager.c)
871 c_sendIOManagerEvent :: Word32 -> IO ()
873 foreign import ccall unsafe "maperrno" -- in Win32Utils.c
876 foreign import stdcall "WaitForSingleObject"
877 c_WaitForSingleObject :: HANDLE -> DWORD -> IO DWORD
880 -- ----------------------------------------------------------------------------
881 -- Unix IO manager thread, using select()
883 startIOManagerThread :: IO ()
884 startIOManagerThread = do
885 allocaArray 2 $ \fds -> do
886 throwErrnoIfMinus1 "startIOManagerThread" (c_pipe fds)
887 rd_end <- peekElemOff fds 0
888 wr_end <- peekElemOff fds 1
889 writeIORef stick (fromIntegral wr_end)
890 c_setIOManagerPipe wr_end
892 allocaBytes sizeofFdSet $ \readfds -> do
893 allocaBytes sizeofFdSet $ \writefds -> do
894 allocaBytes sizeofTimeVal $ \timeval -> do
895 service_loop (fromIntegral rd_end) readfds writefds timeval [] []
899 :: Fd -- listen to this for wakeup calls
906 service_loop wakeup readfds writefds ptimeval old_reqs old_delays = do
908 -- pick up new IO requests
909 new_reqs <- atomicModifyIORef pendingEvents (\a -> ([],a))
910 let reqs = new_reqs ++ old_reqs
912 -- pick up new delay requests
913 new_delays <- atomicModifyIORef pendingDelays (\a -> ([],a))
914 let delays = foldr insertDelay old_delays new_delays
916 -- build the FDSets for select()
920 maxfd <- buildFdSets 0 readfds writefds reqs
922 -- perform the select()
923 let do_select delays = do
924 -- check the current time and wake up any thread in
925 -- threadDelay whose timeout has expired. Also find the
926 -- timeout value for the select() call.
928 (delays', timeout) <- getDelay now ptimeval delays
930 res <- c_select (fromIntegral ((max wakeup maxfd)+1)) readfds writefds
936 _ | err == eINTR -> do_select delays'
937 -- EINTR: just redo the select()
938 _ | err == eBADF -> return (True, delays)
939 -- EBADF: one of the file descriptors is closed or bad,
940 -- we don't know which one, so wake everyone up.
941 _ | otherwise -> throwErrno "select"
942 -- otherwise (ENOMEM or EINVAL) something has gone
943 -- wrong; report the error.
945 return (False,delays')
947 (wakeup_all,delays') <- do_select delays
950 if wakeup_all then return False
952 b <- fdIsSet wakeup readfds
955 else alloca $ \p -> do
956 c_read (fromIntegral wakeup) p 1; return ()
959 _ | s == io_MANAGER_WAKEUP -> return False
960 _ | s == io_MANAGER_DIE -> return True
961 _ -> do handler_tbl <- peek handlers
962 sp <- peekElemOff handler_tbl (fromIntegral s)
963 forkIO (do io <- deRefStablePtr sp; io)
966 if exit then return () else do
968 atomicModifyIORef prodding (\_ -> (False,False))
970 reqs' <- if wakeup_all then do wakeupAll reqs; return []
971 else completeRequests reqs readfds writefds []
973 service_loop wakeup readfds writefds ptimeval reqs' delays'
975 io_MANAGER_WAKEUP = 0xff :: CChar
976 io_MANAGER_DIE = 0xfe :: CChar
979 {-# NOINLINE stick #-}
980 stick = unsafePerformIO (newIORef 0)
982 wakeupIOManager :: IO ()
984 fd <- readIORef stick
985 with io_MANAGER_WAKEUP $ \pbuf -> do
986 c_write (fromIntegral fd) pbuf 1; return ()
988 foreign import ccall "&signal_handlers" handlers :: Ptr (Ptr (StablePtr (IO ())))
990 foreign import ccall "setIOManagerPipe"
991 c_setIOManagerPipe :: CInt -> IO ()
993 -- -----------------------------------------------------------------------------
996 buildFdSets maxfd readfds writefds [] = return maxfd
997 buildFdSets maxfd readfds writefds (Read fd m : reqs)
998 | fd >= fD_SETSIZE = error "buildFdSets: file descriptor out of range"
1001 buildFdSets (max maxfd fd) readfds writefds reqs
1002 buildFdSets maxfd readfds writefds (Write fd m : reqs)
1003 | fd >= fD_SETSIZE = error "buildFdSets: file descriptor out of range"
1006 buildFdSets (max maxfd fd) readfds writefds reqs
1008 completeRequests [] _ _ reqs' = return reqs'
1009 completeRequests (Read fd m : reqs) readfds writefds reqs' = do
1010 b <- fdIsSet fd readfds
1012 then do putMVar m (); completeRequests reqs readfds writefds reqs'
1013 else completeRequests reqs readfds writefds (Read fd m : reqs')
1014 completeRequests (Write fd m : reqs) readfds writefds reqs' = do
1015 b <- fdIsSet fd writefds
1017 then do putMVar m (); completeRequests reqs readfds writefds reqs'
1018 else completeRequests reqs readfds writefds (Write fd m : reqs')
1020 wakeupAll [] = return ()
1021 wakeupAll (Read fd m : reqs) = do putMVar m (); wakeupAll reqs
1022 wakeupAll (Write fd m : reqs) = do putMVar m (); wakeupAll reqs
1024 waitForReadEvent :: Fd -> IO ()
1025 waitForReadEvent fd = do
1027 atomicModifyIORef pendingEvents (\xs -> (Read fd m : xs, ()))
1031 waitForWriteEvent :: Fd -> IO ()
1032 waitForWriteEvent fd = do
1034 atomicModifyIORef pendingEvents (\xs -> (Write fd m : xs, ()))
1038 -- -----------------------------------------------------------------------------
1041 -- Walk the queue of pending delays, waking up any that have passed
1042 -- and return the smallest delay to wait for. The queue of pending
1043 -- delays is kept ordered.
1044 getDelay :: USecs -> Ptr CTimeVal -> [DelayReq] -> IO ([DelayReq], Ptr CTimeVal)
1045 getDelay now ptimeval [] = return ([],nullPtr)
1046 getDelay now ptimeval all@(d : rest)
1048 Delay time m | now >= time -> do
1050 getDelay now ptimeval rest
1051 DelaySTM time t | now >= time -> do
1052 atomically $ writeTVar t True
1053 getDelay now ptimeval rest
1055 setTimevalTicks ptimeval (delayTime d - now)
1056 return (all,ptimeval)
1058 newtype CTimeVal = CTimeVal ()
1060 foreign import ccall unsafe "sizeofTimeVal"
1061 sizeofTimeVal :: Int
1063 foreign import ccall unsafe "setTimevalTicks"
1064 setTimevalTicks :: Ptr CTimeVal -> USecs -> IO ()
1067 On Win32 we're going to have a single Pipe, and a
1068 waitForSingleObject with the delay time. For signals, we send a
1069 byte down the pipe just like on Unix.
1072 -- ----------------------------------------------------------------------------
1073 -- select() interface
1075 -- ToDo: move to System.Posix.Internals?
1077 newtype CFdSet = CFdSet ()
1079 foreign import ccall safe "select"
1080 c_select :: CInt -> Ptr CFdSet -> Ptr CFdSet -> Ptr CFdSet -> Ptr CTimeVal
1083 foreign import ccall unsafe "hsFD_SETSIZE"
1084 c_fD_SETSIZE :: CInt
1087 fD_SETSIZE = fromIntegral c_fD_SETSIZE
1089 foreign import ccall unsafe "hsFD_CLR"
1090 c_fdClr :: CInt -> Ptr CFdSet -> IO ()
1092 fdClr :: Fd -> Ptr CFdSet -> IO ()
1093 fdClr (Fd fd) fdset = c_fdClr fd fdset
1095 foreign import ccall unsafe "hsFD_ISSET"
1096 c_fdIsSet :: CInt -> Ptr CFdSet -> IO CInt
1098 fdIsSet :: Fd -> Ptr CFdSet -> IO CInt
1099 fdIsSet (Fd fd) fdset = c_fdIsSet fd fdset
1101 foreign import ccall unsafe "hsFD_SET"
1102 c_fdSet :: CInt -> Ptr CFdSet -> IO ()
1104 fdSet :: Fd -> Ptr CFdSet -> IO ()
1105 fdSet (Fd fd) fdset = c_fdSet fd fdset
1107 foreign import ccall unsafe "hsFD_ZERO"
1108 fdZero :: Ptr CFdSet -> IO ()
1110 foreign import ccall unsafe "sizeof_fd_set"