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:
26 -- Forking and suchlike
27 , forkIO -- :: IO a -> IO ThreadId
28 , childHandler -- :: Exception -> IO ()
29 , myThreadId -- :: IO ThreadId
30 , killThread -- :: ThreadId -> IO ()
31 , throwTo -- :: ThreadId -> Exception -> IO ()
32 , par -- :: a -> b -> b
33 , pseq -- :: a -> b -> b
35 , labelThread -- :: ThreadId -> String -> IO ()
38 , threadDelay -- :: Int -> IO ()
39 , registerDelay -- :: Int -> IO (TVar Bool)
40 , threadWaitRead -- :: Int -> IO ()
41 , threadWaitWrite -- :: Int -> IO ()
45 , newMVar -- :: a -> IO (MVar a)
46 , newEmptyMVar -- :: IO (MVar a)
47 , takeMVar -- :: MVar a -> IO a
48 , putMVar -- :: MVar a -> a -> IO ()
49 , tryTakeMVar -- :: MVar a -> IO (Maybe a)
50 , tryPutMVar -- :: MVar a -> a -> IO Bool
51 , isEmptyMVar -- :: MVar a -> IO Bool
52 , addMVarFinalizer -- :: MVar a -> IO () -> IO ()
56 , atomically -- :: STM a -> IO a
58 , orElse -- :: STM a -> STM a -> STM a
59 , catchSTM -- :: STM a -> (Exception -> STM a) -> STM a
61 , newTVar -- :: a -> STM (TVar a)
62 , readTVar -- :: TVar a -> STM a
63 , writeTVar -- :: a -> TVar a -> STM ()
64 , unsafeIOToSTM -- :: IO a -> STM a
66 #ifdef mingw32_HOST_OS
67 , asyncRead -- :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
68 , asyncWrite -- :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
69 , asyncDoProc -- :: FunPtr (Ptr a -> IO Int) -> Ptr a -> IO Int
71 , asyncReadBA -- :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int, Int)
72 , asyncWriteBA -- :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int, Int)
75 #ifndef mingw32_HOST_OS
76 , ensureIOManagerIsRunning
80 import System.Posix.Types
81 import System.Posix.Internals
86 import {-# SOURCE #-} GHC.TopHandler ( reportError, reportStackOverflow )
93 import GHC.Num ( Num(..) )
94 import GHC.Real ( fromIntegral, quot )
95 import GHC.Base ( Int(..) )
96 import GHC.Exception ( catchException, Exception(..), AsyncException(..) )
97 import GHC.Pack ( packCString# )
98 import GHC.Ptr ( Ptr(..), plusPtr, FunPtr(..) )
102 infixr 0 `par`, `pseq`
105 %************************************************************************
107 \subsection{@ThreadId@, @par@, and @fork@}
109 %************************************************************************
112 data ThreadId = ThreadId ThreadId# deriving( Typeable )
113 -- ToDo: data ThreadId = ThreadId (Weak ThreadId#)
114 -- But since ThreadId# is unlifted, the Weak type must use open
117 A 'ThreadId' is an abstract type representing a handle to a thread.
118 'ThreadId' is an instance of 'Eq', 'Ord' and 'Show', where
119 the 'Ord' instance implements an arbitrary total ordering over
120 'ThreadId's. The 'Show' instance lets you convert an arbitrary-valued
121 'ThreadId' to string form; showing a 'ThreadId' value is occasionally
122 useful when debugging or diagnosing the behaviour of a concurrent
125 /Note/: in GHC, if you have a 'ThreadId', you essentially have
126 a pointer to the thread itself. This means the thread itself can\'t be
127 garbage collected until you drop the 'ThreadId'.
128 This misfeature will hopefully be corrected at a later date.
130 /Note/: Hugs does not provide any operations on other threads;
131 it defines 'ThreadId' as a synonym for ().
135 This sparks off a new thread to run the 'IO' computation passed as the
136 first argument, and returns the 'ThreadId' of the newly created
139 The new thread will be a lightweight thread; if you want to use a foreign
140 library that uses thread-local storage, use 'forkOS' instead.
142 forkIO :: IO () -> IO ThreadId
143 forkIO action = IO $ \ s ->
144 case (fork# action_plus s) of (# s1, id #) -> (# s1, ThreadId id #)
146 action_plus = catchException action childHandler
148 childHandler :: Exception -> IO ()
149 childHandler err = catchException (real_handler err) childHandler
151 real_handler :: Exception -> IO ()
154 -- ignore thread GC and killThread exceptions:
155 BlockedOnDeadMVar -> return ()
156 BlockedIndefinitely -> return ()
157 AsyncException ThreadKilled -> return ()
159 -- report all others:
160 AsyncException StackOverflow -> reportStackOverflow
161 other -> reportError other
163 {- | 'killThread' terminates the given thread (GHC only).
164 Any work already done by the thread isn\'t
165 lost: the computation is suspended until required by another thread.
166 The memory used by the thread will be garbage collected if it isn\'t
167 referenced from anywhere. The 'killThread' function is defined in
170 > killThread tid = throwTo tid (AsyncException ThreadKilled)
173 killThread :: ThreadId -> IO ()
174 killThread tid = throwTo tid (AsyncException ThreadKilled)
176 {- | 'throwTo' raises an arbitrary exception in the target thread (GHC only).
178 'throwTo' does not return until the exception has been raised in the
179 target thread. The calling thread can thus be certain that the target
180 thread has received the exception. This is a useful property to know
181 when dealing with race conditions: eg. if there are two threads that
182 can kill each other, it is guaranteed that only one of the threads
183 will get to kill the other.
185 If the target thread is currently making a foreign call, then the
186 exception will not be raised (and hence 'throwTo' will not return)
187 until the call has completed. This is the case regardless of whether
188 the call is inside a 'block' or not.
190 throwTo :: ThreadId -> Exception -> IO ()
191 throwTo (ThreadId id) ex = IO $ \ s ->
192 case (killThread# id ex s) of s1 -> (# s1, () #)
194 -- | Returns the 'ThreadId' of the calling thread (GHC only).
195 myThreadId :: IO ThreadId
196 myThreadId = IO $ \s ->
197 case (myThreadId# s) of (# s1, id #) -> (# s1, ThreadId id #)
200 -- |The 'yield' action allows (forces, in a co-operative multitasking
201 -- implementation) a context-switch to any other currently runnable
202 -- threads (if any), and is occasionally useful when implementing
203 -- concurrency abstractions.
206 case (yield# s) of s1 -> (# s1, () #)
208 {- | 'labelThread' stores a string as identifier for this thread if
209 you built a RTS with debugging support. This identifier will be used in
210 the debugging output to make distinction of different threads easier
211 (otherwise you only have the thread state object\'s address in the heap).
213 Other applications like the graphical Concurrent Haskell Debugger
214 (<http://www.informatik.uni-kiel.de/~fhu/chd/>) may choose to overload
215 'labelThread' for their purposes as well.
218 labelThread :: ThreadId -> String -> IO ()
219 labelThread (ThreadId t) str = IO $ \ s ->
220 let ps = packCString# str
221 adr = byteArrayContents# ps in
222 case (labelThread# t adr s) of s1 -> (# s1, () #)
224 -- Nota Bene: 'pseq' used to be 'seq'
225 -- but 'seq' is now defined in PrelGHC
227 -- "pseq" is defined a bit weirdly (see below)
229 -- The reason for the strange "lazy" call is that
230 -- it fools the compiler into thinking that pseq and par are non-strict in
231 -- their second argument (even if it inlines pseq at the call site).
232 -- If it thinks pseq is strict in "y", then it often evaluates
233 -- "y" before "x", which is totally wrong.
237 pseq x y = x `seq` lazy y
241 par x y = case (par# x) of { _ -> lazy y }
245 %************************************************************************
247 \subsection[stm]{Transactional heap operations}
249 %************************************************************************
251 TVars are shared memory locations which support atomic memory
255 newtype STM a = STM (State# RealWorld -> (# State# RealWorld, a #)) deriving( Typeable )
257 unSTM :: STM a -> (State# RealWorld -> (# State# RealWorld, a #))
260 instance Functor STM where
261 fmap f x = x >>= (return . f)
263 instance Monad STM where
264 {-# INLINE return #-}
268 return x = returnSTM x
269 m >>= k = bindSTM m k
271 bindSTM :: STM a -> (a -> STM b) -> STM b
272 bindSTM (STM m) k = STM ( \s ->
274 (# new_s, a #) -> unSTM (k a) new_s
277 thenSTM :: STM a -> STM b -> STM b
278 thenSTM (STM m) k = STM ( \s ->
280 (# new_s, a #) -> unSTM k new_s
283 returnSTM :: a -> STM a
284 returnSTM x = STM (\s -> (# s, x #))
286 -- | Unsafely performs IO in the STM monad.
287 unsafeIOToSTM :: IO a -> STM a
288 unsafeIOToSTM (IO m) = STM m
290 -- |Perform a series of STM actions atomically.
291 atomically :: STM a -> IO a
292 atomically (STM m) = IO (\s -> (atomically# m) s )
294 -- |Retry execution of the current memory transaction because it has seen
295 -- values in TVars which mean that it should not continue (e.g. the TVars
296 -- represent a shared buffer that is now empty). The implementation may
297 -- block the thread until one of the TVars that it has read from has been
300 retry = STM $ \s# -> retry# s#
302 -- |Compose two alternative STM actions. If the first action completes without
303 -- retrying then it forms the result of the orElse. Otherwise, if the first
304 -- action retries, then the second action is tried in its place. If both actions
305 -- retry then the orElse as a whole retries.
306 orElse :: STM a -> STM a -> STM a
307 orElse (STM m) e = STM $ \s -> catchRetry# m (unSTM e) s
309 -- |Exception handling within STM actions.
310 catchSTM :: STM a -> (Exception -> STM a) -> STM a
311 catchSTM (STM m) k = STM $ \s -> catchSTM# m (\ex -> unSTM (k ex)) s
313 data TVar a = TVar (TVar# RealWorld a) deriving( Typeable )
315 instance Eq (TVar a) where
316 (TVar tvar1#) == (TVar tvar2#) = sameTVar# tvar1# tvar2#
318 -- |Create a new TVar holding a value supplied
319 newTVar :: a -> STM (TVar a)
320 newTVar val = STM $ \s1# ->
321 case newTVar# val s1# of
322 (# s2#, tvar# #) -> (# s2#, TVar tvar# #)
324 -- |Return the current value stored in a TVar
325 readTVar :: TVar a -> STM a
326 readTVar (TVar tvar#) = STM $ \s# -> readTVar# tvar# s#
328 -- |Write the supplied value into a TVar
329 writeTVar :: TVar a -> a -> STM ()
330 writeTVar (TVar tvar#) val = STM $ \s1# ->
331 case writeTVar# tvar# val s1# of
336 %************************************************************************
338 \subsection[mvars]{M-Structures}
340 %************************************************************************
342 M-Vars are rendezvous points for concurrent threads. They begin
343 empty, and any attempt to read an empty M-Var blocks. When an M-Var
344 is written, a single blocked thread may be freed. Reading an M-Var
345 toggles its state from full back to empty. Therefore, any value
346 written to an M-Var may only be read once. Multiple reads and writes
347 are allowed, but there must be at least one read between any two
351 --Defined in IOBase to avoid cycle: data MVar a = MVar (SynchVar# RealWorld a)
353 -- |Create an 'MVar' which is initially empty.
354 newEmptyMVar :: IO (MVar a)
355 newEmptyMVar = IO $ \ s# ->
357 (# s2#, svar# #) -> (# s2#, MVar svar# #)
359 -- |Create an 'MVar' which contains the supplied value.
360 newMVar :: a -> IO (MVar a)
362 newEmptyMVar >>= \ mvar ->
363 putMVar mvar value >>
366 -- |Return the contents of the 'MVar'. If the 'MVar' is currently
367 -- empty, 'takeMVar' will wait until it is full. After a 'takeMVar',
368 -- the 'MVar' is left empty.
370 -- If several threads are competing to take the same 'MVar', one is chosen
371 -- to continue at random when the 'MVar' becomes full.
372 takeMVar :: MVar a -> IO a
373 takeMVar (MVar mvar#) = IO $ \ s# -> takeMVar# mvar# s#
375 -- |Put a value into an 'MVar'. If the 'MVar' is currently full,
376 -- 'putMVar' will wait until it becomes empty.
378 -- If several threads are competing to fill the same 'MVar', one is
379 -- chosen to continue at random when the 'MVar' becomes empty.
380 putMVar :: MVar a -> a -> IO ()
381 putMVar (MVar mvar#) x = IO $ \ s# ->
382 case putMVar# mvar# x s# of
385 -- |A non-blocking version of 'takeMVar'. The 'tryTakeMVar' function
386 -- returns immediately, with 'Nothing' if the 'MVar' was empty, or
387 -- @'Just' a@ if the 'MVar' was full with contents @a@. After 'tryTakeMVar',
388 -- the 'MVar' is left empty.
389 tryTakeMVar :: MVar a -> IO (Maybe a)
390 tryTakeMVar (MVar m) = IO $ \ s ->
391 case tryTakeMVar# m s of
392 (# s, 0#, _ #) -> (# s, Nothing #) -- MVar is empty
393 (# s, _, a #) -> (# s, Just a #) -- MVar is full
395 -- |A non-blocking version of 'putMVar'. The 'tryPutMVar' function
396 -- attempts to put the value @a@ into the 'MVar', returning 'True' if
397 -- it was successful, or 'False' otherwise.
398 tryPutMVar :: MVar a -> a -> IO Bool
399 tryPutMVar (MVar mvar#) x = IO $ \ s# ->
400 case tryPutMVar# mvar# x s# of
401 (# s, 0# #) -> (# s, False #)
402 (# s, _ #) -> (# s, True #)
404 -- |Check whether a given 'MVar' is empty.
406 -- Notice that the boolean value returned is just a snapshot of
407 -- the state of the MVar. By the time you get to react on its result,
408 -- the MVar may have been filled (or emptied) - so be extremely
409 -- careful when using this operation. Use 'tryTakeMVar' instead if possible.
410 isEmptyMVar :: MVar a -> IO Bool
411 isEmptyMVar (MVar mv#) = IO $ \ s# ->
412 case isEmptyMVar# mv# s# of
413 (# s2#, flg #) -> (# s2#, not (flg ==# 0#) #)
415 -- |Add a finalizer to an 'MVar' (GHC only). See "Foreign.ForeignPtr" and
416 -- "System.Mem.Weak" for more about finalizers.
417 addMVarFinalizer :: MVar a -> IO () -> IO ()
418 addMVarFinalizer (MVar m) finalizer =
419 IO $ \s -> case mkWeak# m () finalizer s of { (# s1, w #) -> (# s1, () #) }
423 %************************************************************************
425 \subsection{Thread waiting}
427 %************************************************************************
430 #ifdef mingw32_HOST_OS
432 -- Note: threadDelay, threadWaitRead and threadWaitWrite aren't really functional
433 -- on Win32, but left in there because lib code (still) uses them (the manner
434 -- in which they're used doesn't cause problems on a Win32 platform though.)
436 asyncRead :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
437 asyncRead (I# fd) (I# isSock) (I# len) (Ptr buf) =
438 IO $ \s -> case asyncRead# fd isSock len buf s of
439 (# s, len#, err# #) -> (# s, (I# len#, I# err#) #)
441 asyncWrite :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
442 asyncWrite (I# fd) (I# isSock) (I# len) (Ptr buf) =
443 IO $ \s -> case asyncWrite# fd isSock len buf s of
444 (# s, len#, err# #) -> (# s, (I# len#, I# err#) #)
446 asyncDoProc :: FunPtr (Ptr a -> IO Int) -> Ptr a -> IO Int
447 asyncDoProc (FunPtr proc) (Ptr param) =
448 -- the 'length' value is ignored; simplifies implementation of
449 -- the async*# primops to have them all return the same result.
450 IO $ \s -> case asyncDoProc# proc param s of
451 (# s, len#, err# #) -> (# s, I# err# #)
453 -- to aid the use of these primops by the IO Handle implementation,
454 -- provide the following convenience funs:
456 -- this better be a pinned byte array!
457 asyncReadBA :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int,Int)
458 asyncReadBA fd isSock len off bufB =
459 asyncRead fd isSock len ((Ptr (byteArrayContents# (unsafeCoerce# bufB))) `plusPtr` off)
461 asyncWriteBA :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int,Int)
462 asyncWriteBA fd isSock len off bufB =
463 asyncWrite fd isSock len ((Ptr (byteArrayContents# (unsafeCoerce# bufB))) `plusPtr` off)
467 -- -----------------------------------------------------------------------------
470 -- | Block the current thread until data is available to read on the
471 -- given file descriptor (GHC only).
472 threadWaitRead :: Fd -> IO ()
474 #ifndef mingw32_HOST_OS
475 | threaded = waitForReadEvent fd
477 | otherwise = IO $ \s ->
478 case fromIntegral fd of { I# fd# ->
479 case waitRead# fd# s of { s -> (# s, () #)
482 -- | Block the current thread until data can be written to the
483 -- given file descriptor (GHC only).
484 threadWaitWrite :: Fd -> IO ()
486 #ifndef mingw32_HOST_OS
487 | threaded = waitForWriteEvent fd
489 | otherwise = IO $ \s ->
490 case fromIntegral fd of { I# fd# ->
491 case waitWrite# fd# s of { s -> (# s, () #)
494 -- | Suspends the current thread for a given number of microseconds
497 -- Note that the resolution used by the Haskell runtime system's
498 -- internal timer is 1\/50 second, and 'threadDelay' will round its
499 -- argument up to the nearest multiple of this resolution.
501 -- There is no guarantee that the thread will be rescheduled promptly
502 -- when the delay has expired, but the thread will never continue to
503 -- run /earlier/ than specified.
505 threadDelay :: Int -> IO ()
507 #ifndef mingw32_HOST_OS
508 | threaded = waitForDelayEvent time
510 | threaded = c_Sleep (fromIntegral (time `quot` 1000))
512 | otherwise = IO $ \s ->
513 case fromIntegral time of { I# time# ->
514 case delay# time# s of { s -> (# s, () #)
518 #ifndef mingw32_HOST_OS
519 | threaded = waitForDelayEventSTM usecs
520 | otherwise = error "registerDelay: requires -threaded"
522 = error "registerDelay: not currently supported on Windows"
525 -- On Windows, we just make a safe call to 'Sleep' to implement threadDelay.
526 #ifdef mingw32_HOST_OS
527 foreign import stdcall safe "Sleep" c_Sleep :: CInt -> IO ()
530 foreign import ccall unsafe "rtsSupportsBoundThreads" threaded :: Bool
532 -- ----------------------------------------------------------------------------
533 -- Threaded RTS implementation of threadWaitRead, threadWaitWrite, threadDelay
535 -- In the threaded RTS, we employ a single IO Manager thread to wait
536 -- for all outstanding IO requests (threadWaitRead,threadWaitWrite)
537 -- and delays (threadDelay).
539 -- We can do this because in the threaded RTS the IO Manager can make
540 -- a non-blocking call to select(), so we don't have to do select() in
541 -- the scheduler as we have to in the non-threaded RTS. We get performance
542 -- benefits from doing it this way, because we only have to restart the select()
543 -- when a new request arrives, rather than doing one select() each time
544 -- around the scheduler loop. Furthermore, the scheduler can be simplified
545 -- by not having to check for completed IO requests.
547 -- Issues, possible problems:
549 -- - we might want bound threads to just do the blocking
550 -- operation rather than communicating with the IO manager
551 -- thread. This would prevent simgle-threaded programs which do
552 -- IO from requiring multiple OS threads. However, it would also
553 -- prevent bound threads waiting on IO from being killed or sent
556 -- - Apprently exec() doesn't work on Linux in a multithreaded program.
557 -- I couldn't repeat this.
559 -- - How do we handle signal delivery in the multithreaded RTS?
561 -- - forkProcess will kill the IO manager thread. Let's just
562 -- hope we don't need to do any blocking IO between fork & exec.
564 #ifndef mingw32_HOST_OS
567 = Read {-# UNPACK #-} !Fd {-# UNPACK #-} !(MVar ())
568 | Write {-# UNPACK #-} !Fd {-# UNPACK #-} !(MVar ())
571 = Delay {-# UNPACK #-} !Int {-# UNPACK #-} !(MVar ())
572 | DelaySTM {-# UNPACK #-} !Int {-# UNPACK #-} !(TVar Bool)
574 pendingEvents :: IORef [IOReq]
575 pendingDelays :: IORef [DelayReq]
576 -- could use a strict list or array here
577 {-# NOINLINE pendingEvents #-}
578 {-# NOINLINE pendingDelays #-}
579 (pendingEvents,pendingDelays) = unsafePerformIO $ do
584 -- the first time we schedule an IO request, the service thread
585 -- will be created (cool, huh?)
587 ensureIOManagerIsRunning :: IO ()
588 ensureIOManagerIsRunning
589 | threaded = seq pendingEvents $ return ()
590 | otherwise = return ()
592 startIOManagerThread :: IO ()
593 startIOManagerThread = do
594 allocaArray 2 $ \fds -> do
595 throwErrnoIfMinus1 "startIOManagerThread" (c_pipe fds)
596 rd_end <- peekElemOff fds 0
597 wr_end <- peekElemOff fds 1
598 writeIORef stick (fromIntegral wr_end)
599 c_setIOManagerPipe wr_end
601 allocaBytes sizeofFdSet $ \readfds -> do
602 allocaBytes sizeofFdSet $ \writefds -> do
603 allocaBytes sizeofTimeVal $ \timeval -> do
604 service_loop (fromIntegral rd_end) readfds writefds timeval [] []
608 :: Fd -- listen to this for wakeup calls
615 service_loop wakeup readfds writefds ptimeval old_reqs old_delays = do
617 -- pick up new IO requests
618 new_reqs <- atomicModifyIORef pendingEvents (\a -> ([],a))
619 let reqs = new_reqs ++ old_reqs
621 -- pick up new delay requests
622 new_delays <- atomicModifyIORef pendingDelays (\a -> ([],a))
623 let delays = foldr insertDelay old_delays new_delays
625 -- build the FDSets for select()
629 maxfd <- buildFdSets 0 readfds writefds reqs
631 -- perform the select()
632 let do_select delays = do
633 -- check the current time and wake up any thread in
634 -- threadDelay whose timeout has expired. Also find the
635 -- timeout value for the select() call.
637 (delays', timeout) <- getDelay now ptimeval delays
639 res <- c_select ((max wakeup maxfd)+1) readfds writefds
645 then do_select delays'
646 else return (res,delays')
650 (res,delays') <- do_select delays
651 -- ToDo: check result
653 b <- fdIsSet wakeup readfds
656 else alloca $ \p -> do
657 c_read (fromIntegral wakeup) p 1; return ()
661 else do handler_tbl <- peek handlers
662 sp <- peekElemOff handler_tbl (fromIntegral s)
663 forkIO (do io <- deRefStablePtr sp; io)
667 putMVar prodding False
669 reqs' <- completeRequests reqs readfds writefds []
670 service_loop wakeup readfds writefds ptimeval reqs' delays'
673 {-# NOINLINE stick #-}
674 stick = unsafePerformIO (newIORef 0)
676 prodding :: MVar Bool
677 {-# NOINLINE prodding #-}
678 prodding = unsafePerformIO (newMVar False)
680 prodServiceThread :: IO ()
681 prodServiceThread = do
682 b <- takeMVar prodding
684 then do fd <- readIORef stick
685 with 0xff $ \pbuf -> do c_write (fromIntegral fd) pbuf 1; return ()
687 putMVar prodding True
689 foreign import ccall "&signal_handlers" handlers :: Ptr (Ptr (StablePtr (IO ())))
691 foreign import ccall "setIOManagerPipe"
692 c_setIOManagerPipe :: CInt -> IO ()
694 -- -----------------------------------------------------------------------------
697 buildFdSets maxfd readfds writefds [] = return maxfd
698 buildFdSets maxfd readfds writefds (Read fd m : reqs)
699 | fd >= fD_SETSIZE = error "buildFdSets: file descriptor out of range"
702 buildFdSets (max maxfd fd) readfds writefds reqs
703 buildFdSets maxfd readfds writefds (Write fd m : reqs)
704 | fd >= fD_SETSIZE = error "buildFdSets: file descriptor out of range"
707 buildFdSets (max maxfd fd) readfds writefds reqs
709 completeRequests [] _ _ reqs' = return reqs'
710 completeRequests (Read fd m : reqs) readfds writefds reqs' = do
711 b <- fdIsSet fd readfds
713 then do putMVar m (); completeRequests reqs readfds writefds reqs'
714 else completeRequests reqs readfds writefds (Read fd m : reqs')
715 completeRequests (Write fd m : reqs) readfds writefds reqs' = do
716 b <- fdIsSet fd writefds
718 then do putMVar m (); completeRequests reqs readfds writefds reqs'
719 else completeRequests reqs readfds writefds (Write fd m : reqs')
721 waitForReadEvent :: Fd -> IO ()
722 waitForReadEvent fd = do
724 atomicModifyIORef pendingEvents (\xs -> (Read fd m : xs, ()))
728 waitForWriteEvent :: Fd -> IO ()
729 waitForWriteEvent fd = do
731 atomicModifyIORef pendingEvents (\xs -> (Write fd m : xs, ()))
735 -- XXX: move into GHC.IOBase from Data.IORef?
736 atomicModifyIORef :: IORef a -> (a -> (a,b)) -> IO b
737 atomicModifyIORef (IORef (STRef r#)) f = IO $ \s -> atomicModifyMutVar# r# f s
739 -- -----------------------------------------------------------------------------
742 waitForDelayEvent :: Int -> IO ()
743 waitForDelayEvent usecs = do
746 let target = now + usecs `quot` tick_usecs
747 atomicModifyIORef pendingDelays (\xs -> (Delay target m : xs, ()))
751 -- Delays for use in STM
752 waitForDelayEventSTM :: Int -> IO (TVar Bool)
753 waitForDelayEventSTM usecs = do
754 t <- atomically $ newTVar False
756 let target = now + usecs `quot` tick_usecs
757 atomicModifyIORef pendingDelays (\xs -> (DelaySTM target t : xs, ()))
761 -- Walk the queue of pending delays, waking up any that have passed
762 -- and return the smallest delay to wait for. The queue of pending
763 -- delays is kept ordered.
764 getDelay :: Ticks -> Ptr CTimeVal -> [DelayReq] -> IO ([DelayReq], Ptr CTimeVal)
765 getDelay now ptimeval [] = return ([],nullPtr)
766 getDelay now ptimeval all@(d : rest)
768 Delay time m | now >= time -> do
770 getDelay now ptimeval rest
771 DelaySTM time t | now >= time -> do
772 atomically $ writeTVar t True
773 getDelay now ptimeval rest
775 setTimevalTicks ptimeval (delayTime d - now)
776 return (all,ptimeval)
778 insertDelay :: DelayReq -> [DelayReq] -> [DelayReq]
779 insertDelay d [] = [d]
780 insertDelay d1 ds@(d2 : rest)
781 | delayTime d1 <= delayTime d2 = d1 : ds
782 | otherwise = d2 : insertDelay d1 rest
784 delayTime (Delay t _) = t
785 delayTime (DelaySTM t _) = t
788 tick_freq = 50 :: Ticks -- accuracy of threadDelay (ticks per sec)
789 tick_usecs = 1000000 `quot` tick_freq :: Int
791 newtype CTimeVal = CTimeVal ()
793 foreign import ccall unsafe "sizeofTimeVal"
796 foreign import ccall unsafe "getTicksOfDay"
797 getTicksOfDay :: IO Ticks
799 foreign import ccall unsafe "setTimevalTicks"
800 setTimevalTicks :: Ptr CTimeVal -> Ticks -> IO ()
802 -- ----------------------------------------------------------------------------
803 -- select() interface
805 -- ToDo: move to System.Posix.Internals?
807 newtype CFdSet = CFdSet ()
809 foreign import ccall safe "select"
810 c_select :: Fd -> Ptr CFdSet -> Ptr CFdSet -> Ptr CFdSet -> Ptr CTimeVal
813 foreign import ccall unsafe "hsFD_SETSIZE"
816 foreign import ccall unsafe "hsFD_CLR"
817 fdClr :: Fd -> Ptr CFdSet -> IO ()
819 foreign import ccall unsafe "hsFD_ISSET"
820 fdIsSet :: Fd -> Ptr CFdSet -> IO CInt
822 foreign import ccall unsafe "hsFD_SET"
823 fdSet :: Fd -> Ptr CFdSet -> IO ()
825 foreign import ccall unsafe "hsFD_ZERO"
826 fdZero :: Ptr CFdSet -> IO ()
828 foreign import ccall unsafe "sizeof_fd_set"