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 , newTVarIO -- :: a -> STM (TVar a)
63 , readTVar -- :: TVar a -> STM a
64 , writeTVar -- :: a -> TVar a -> STM ()
65 , unsafeIOToSTM -- :: IO a -> STM a
67 #ifdef mingw32_HOST_OS
68 , asyncRead -- :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
69 , asyncWrite -- :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
70 , asyncDoProc -- :: FunPtr (Ptr a -> IO Int) -> Ptr a -> IO Int
72 , asyncReadBA -- :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int, Int)
73 , asyncWriteBA -- :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int, Int)
76 #ifndef mingw32_HOST_OS
77 , ensureIOManagerIsRunning
81 import System.Posix.Types
82 import System.Posix.Internals
87 import {-# SOURCE #-} GHC.TopHandler ( reportError, reportStackOverflow )
94 import GHC.Num ( Num(..) )
95 import GHC.Real ( fromIntegral, quot )
96 import GHC.Base ( Int(..) )
97 import GHC.Exception ( catchException, Exception(..), AsyncException(..) )
98 import GHC.Pack ( packCString# )
99 import GHC.Ptr ( Ptr(..), plusPtr, FunPtr(..) )
103 infixr 0 `par`, `pseq`
106 %************************************************************************
108 \subsection{@ThreadId@, @par@, and @fork@}
110 %************************************************************************
113 data ThreadId = ThreadId ThreadId# deriving( Typeable )
114 -- ToDo: data ThreadId = ThreadId (Weak ThreadId#)
115 -- But since ThreadId# is unlifted, the Weak type must use open
118 A 'ThreadId' is an abstract type representing a handle to a thread.
119 'ThreadId' is an instance of 'Eq', 'Ord' and 'Show', where
120 the 'Ord' instance implements an arbitrary total ordering over
121 'ThreadId's. The 'Show' instance lets you convert an arbitrary-valued
122 'ThreadId' to string form; showing a 'ThreadId' value is occasionally
123 useful when debugging or diagnosing the behaviour of a concurrent
126 /Note/: in GHC, if you have a 'ThreadId', you essentially have
127 a pointer to the thread itself. This means the thread itself can\'t be
128 garbage collected until you drop the 'ThreadId'.
129 This misfeature will hopefully be corrected at a later date.
131 /Note/: Hugs does not provide any operations on other threads;
132 it defines 'ThreadId' as a synonym for ().
136 This sparks off a new thread to run the 'IO' computation passed as the
137 first argument, and returns the 'ThreadId' of the newly created
140 The new thread will be a lightweight thread; if you want to use a foreign
141 library that uses thread-local storage, use 'forkOS' instead.
143 forkIO :: IO () -> IO ThreadId
144 forkIO action = IO $ \ s ->
145 case (fork# action_plus s) of (# s1, id #) -> (# s1, ThreadId id #)
147 action_plus = catchException action childHandler
149 childHandler :: Exception -> IO ()
150 childHandler err = catchException (real_handler err) childHandler
152 real_handler :: Exception -> IO ()
155 -- ignore thread GC and killThread exceptions:
156 BlockedOnDeadMVar -> return ()
157 BlockedIndefinitely -> return ()
158 AsyncException ThreadKilled -> return ()
160 -- report all others:
161 AsyncException StackOverflow -> reportStackOverflow
162 other -> reportError other
164 {- | 'killThread' terminates the given thread (GHC only).
165 Any work already done by the thread isn\'t
166 lost: the computation is suspended until required by another thread.
167 The memory used by the thread will be garbage collected if it isn\'t
168 referenced from anywhere. The 'killThread' function is defined in
171 > killThread tid = throwTo tid (AsyncException ThreadKilled)
174 killThread :: ThreadId -> IO ()
175 killThread tid = throwTo tid (AsyncException ThreadKilled)
177 {- | 'throwTo' raises an arbitrary exception in the target thread (GHC only).
179 'throwTo' does not return until the exception has been raised in the
180 target thread. The calling thread can thus be certain that the target
181 thread has received the exception. This is a useful property to know
182 when dealing with race conditions: eg. if there are two threads that
183 can kill each other, it is guaranteed that only one of the threads
184 will get to kill the other.
186 If the target thread is currently making a foreign call, then the
187 exception will not be raised (and hence 'throwTo' will not return)
188 until the call has completed. This is the case regardless of whether
189 the call is inside a 'block' or not.
191 throwTo :: ThreadId -> Exception -> IO ()
192 throwTo (ThreadId id) ex = IO $ \ s ->
193 case (killThread# id ex s) of s1 -> (# s1, () #)
195 -- | Returns the 'ThreadId' of the calling thread (GHC only).
196 myThreadId :: IO ThreadId
197 myThreadId = IO $ \s ->
198 case (myThreadId# s) of (# s1, id #) -> (# s1, ThreadId id #)
201 -- |The 'yield' action allows (forces, in a co-operative multitasking
202 -- implementation) a context-switch to any other currently runnable
203 -- threads (if any), and is occasionally useful when implementing
204 -- concurrency abstractions.
207 case (yield# s) of s1 -> (# s1, () #)
209 {- | 'labelThread' stores a string as identifier for this thread if
210 you built a RTS with debugging support. This identifier will be used in
211 the debugging output to make distinction of different threads easier
212 (otherwise you only have the thread state object\'s address in the heap).
214 Other applications like the graphical Concurrent Haskell Debugger
215 (<http://www.informatik.uni-kiel.de/~fhu/chd/>) may choose to overload
216 'labelThread' for their purposes as well.
219 labelThread :: ThreadId -> String -> IO ()
220 labelThread (ThreadId t) str = IO $ \ s ->
221 let ps = packCString# str
222 adr = byteArrayContents# ps in
223 case (labelThread# t adr s) of s1 -> (# s1, () #)
225 -- Nota Bene: 'pseq' used to be 'seq'
226 -- but 'seq' is now defined in PrelGHC
228 -- "pseq" is defined a bit weirdly (see below)
230 -- The reason for the strange "lazy" call is that
231 -- it fools the compiler into thinking that pseq and par are non-strict in
232 -- their second argument (even if it inlines pseq at the call site).
233 -- If it thinks pseq is strict in "y", then it often evaluates
234 -- "y" before "x", which is totally wrong.
238 pseq x y = x `seq` lazy y
242 par x y = case (par# x) of { _ -> lazy y }
246 %************************************************************************
248 \subsection[stm]{Transactional heap operations}
250 %************************************************************************
252 TVars are shared memory locations which support atomic memory
256 newtype STM a = STM (State# RealWorld -> (# State# RealWorld, a #)) deriving( Typeable )
258 unSTM :: STM a -> (State# RealWorld -> (# State# RealWorld, a #))
261 instance Functor STM where
262 fmap f x = x >>= (return . f)
264 instance Monad STM where
265 {-# INLINE return #-}
269 return x = returnSTM x
270 m >>= k = bindSTM m k
272 bindSTM :: STM a -> (a -> STM b) -> STM b
273 bindSTM (STM m) k = STM ( \s ->
275 (# new_s, a #) -> unSTM (k a) new_s
278 thenSTM :: STM a -> STM b -> STM b
279 thenSTM (STM m) k = STM ( \s ->
281 (# new_s, a #) -> unSTM k new_s
284 returnSTM :: a -> STM a
285 returnSTM x = STM (\s -> (# s, x #))
287 -- | Unsafely performs IO in the STM monad.
288 unsafeIOToSTM :: IO a -> STM a
289 unsafeIOToSTM (IO m) = STM m
291 -- |Perform a series of STM actions atomically.
292 atomically :: STM a -> IO a
293 atomically (STM m) = IO (\s -> (atomically# m) s )
295 -- |Retry execution of the current memory transaction because it has seen
296 -- values in TVars which mean that it should not continue (e.g. the TVars
297 -- represent a shared buffer that is now empty). The implementation may
298 -- block the thread until one of the TVars that it has read from has been
301 retry = STM $ \s# -> retry# s#
303 -- |Compose two alternative STM actions. If the first action completes without
304 -- retrying then it forms the result of the orElse. Otherwise, if the first
305 -- action retries, then the second action is tried in its place. If both actions
306 -- retry then the orElse as a whole retries.
307 orElse :: STM a -> STM a -> STM a
308 orElse (STM m) e = STM $ \s -> catchRetry# m (unSTM e) s
310 -- |Exception handling within STM actions.
311 catchSTM :: STM a -> (Exception -> STM a) -> STM a
312 catchSTM (STM m) k = STM $ \s -> catchSTM# m (\ex -> unSTM (k ex)) s
314 data TVar a = TVar (TVar# RealWorld a) deriving( Typeable )
316 instance Eq (TVar a) where
317 (TVar tvar1#) == (TVar tvar2#) = sameTVar# tvar1# tvar2#
319 -- |Create a new TVar holding a value supplied
320 newTVar :: a -> STM (TVar a)
321 newTVar val = STM $ \s1# ->
322 case newTVar# val s1# of
323 (# s2#, tvar# #) -> (# s2#, TVar tvar# #)
325 -- |@IO@ version of 'newTVar'. This is useful for creating top-level
326 -- 'TVar's using 'System.IO.Unsafe.unsafePerformIO', because using
327 -- 'atomically' inside 'System.IO.Unsafe.unsafePerformIO' isn't
329 newTVarIO :: a -> IO (TVar a)
330 newTVarIO val = IO $ \s1# ->
331 case newTVar# val s1# of
332 (# s2#, tvar# #) -> (# s2#, TVar tvar# #)
334 -- |Return the current value stored in a TVar
335 readTVar :: TVar a -> STM a
336 readTVar (TVar tvar#) = STM $ \s# -> readTVar# tvar# s#
338 -- |Write the supplied value into a TVar
339 writeTVar :: TVar a -> a -> STM ()
340 writeTVar (TVar tvar#) val = STM $ \s1# ->
341 case writeTVar# tvar# val s1# of
346 %************************************************************************
348 \subsection[mvars]{M-Structures}
350 %************************************************************************
352 M-Vars are rendezvous points for concurrent threads. They begin
353 empty, and any attempt to read an empty M-Var blocks. When an M-Var
354 is written, a single blocked thread may be freed. Reading an M-Var
355 toggles its state from full back to empty. Therefore, any value
356 written to an M-Var may only be read once. Multiple reads and writes
357 are allowed, but there must be at least one read between any two
361 --Defined in IOBase to avoid cycle: data MVar a = MVar (SynchVar# RealWorld a)
363 -- |Create an 'MVar' which is initially empty.
364 newEmptyMVar :: IO (MVar a)
365 newEmptyMVar = IO $ \ s# ->
367 (# s2#, svar# #) -> (# s2#, MVar svar# #)
369 -- |Create an 'MVar' which contains the supplied value.
370 newMVar :: a -> IO (MVar a)
372 newEmptyMVar >>= \ mvar ->
373 putMVar mvar value >>
376 -- |Return the contents of the 'MVar'. If the 'MVar' is currently
377 -- empty, 'takeMVar' will wait until it is full. After a 'takeMVar',
378 -- the 'MVar' is left empty.
380 -- There are two further important properties of 'takeMVar':
382 -- * 'takeMVar' is single-wakeup. That is, if there are multiple
383 -- threads blocked in 'takeMVar', and the 'MVar' becomes full,
384 -- only one thread will be woken up. The runtime guarantees that
385 -- the woken thread completes its 'takeMVar' operation.
387 -- * When multiple threads are blocked on an 'MVar', they are
388 -- woken up in FIFO order. This is useful for providing
389 -- fairness properties of abstractions built using 'MVar's.
391 takeMVar :: MVar a -> IO a
392 takeMVar (MVar mvar#) = IO $ \ s# -> takeMVar# mvar# s#
394 -- |Put a value into an 'MVar'. If the 'MVar' is currently full,
395 -- 'putMVar' will wait until it becomes empty.
397 -- There are two further important properties of 'putMVar':
399 -- * 'putMVar' is single-wakeup. That is, if there are multiple
400 -- threads blocked in 'putMVar', and the 'MVar' becomes empty,
401 -- only one thread will be woken up. The runtime guarantees that
402 -- the woken thread completes its 'putMVar' operation.
404 -- * When multiple threads are blocked on an 'MVar', they are
405 -- woken up in FIFO order. This is useful for providing
406 -- fairness properties of abstractions built using 'MVar's.
408 putMVar :: MVar a -> a -> IO ()
409 putMVar (MVar mvar#) x = IO $ \ s# ->
410 case putMVar# mvar# x s# of
413 -- |A non-blocking version of 'takeMVar'. The 'tryTakeMVar' function
414 -- returns immediately, with 'Nothing' if the 'MVar' was empty, or
415 -- @'Just' a@ if the 'MVar' was full with contents @a@. After 'tryTakeMVar',
416 -- the 'MVar' is left empty.
417 tryTakeMVar :: MVar a -> IO (Maybe a)
418 tryTakeMVar (MVar m) = IO $ \ s ->
419 case tryTakeMVar# m s of
420 (# s, 0#, _ #) -> (# s, Nothing #) -- MVar is empty
421 (# s, _, a #) -> (# s, Just a #) -- MVar is full
423 -- |A non-blocking version of 'putMVar'. The 'tryPutMVar' function
424 -- attempts to put the value @a@ into the 'MVar', returning 'True' if
425 -- it was successful, or 'False' otherwise.
426 tryPutMVar :: MVar a -> a -> IO Bool
427 tryPutMVar (MVar mvar#) x = IO $ \ s# ->
428 case tryPutMVar# mvar# x s# of
429 (# s, 0# #) -> (# s, False #)
430 (# s, _ #) -> (# s, True #)
432 -- |Check whether a given 'MVar' is empty.
434 -- Notice that the boolean value returned is just a snapshot of
435 -- the state of the MVar. By the time you get to react on its result,
436 -- the MVar may have been filled (or emptied) - so be extremely
437 -- careful when using this operation. Use 'tryTakeMVar' instead if possible.
438 isEmptyMVar :: MVar a -> IO Bool
439 isEmptyMVar (MVar mv#) = IO $ \ s# ->
440 case isEmptyMVar# mv# s# of
441 (# s2#, flg #) -> (# s2#, not (flg ==# 0#) #)
443 -- |Add a finalizer to an 'MVar' (GHC only). See "Foreign.ForeignPtr" and
444 -- "System.Mem.Weak" for more about finalizers.
445 addMVarFinalizer :: MVar a -> IO () -> IO ()
446 addMVarFinalizer (MVar m) finalizer =
447 IO $ \s -> case mkWeak# m () finalizer s of { (# s1, w #) -> (# s1, () #) }
451 %************************************************************************
453 \subsection{Thread waiting}
455 %************************************************************************
458 #ifdef mingw32_HOST_OS
460 -- Note: threadDelay, threadWaitRead and threadWaitWrite aren't really functional
461 -- on Win32, but left in there because lib code (still) uses them (the manner
462 -- in which they're used doesn't cause problems on a Win32 platform though.)
464 asyncRead :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
465 asyncRead (I# fd) (I# isSock) (I# len) (Ptr buf) =
466 IO $ \s -> case asyncRead# fd isSock len buf s of
467 (# s, len#, err# #) -> (# s, (I# len#, I# err#) #)
469 asyncWrite :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
470 asyncWrite (I# fd) (I# isSock) (I# len) (Ptr buf) =
471 IO $ \s -> case asyncWrite# fd isSock len buf s of
472 (# s, len#, err# #) -> (# s, (I# len#, I# err#) #)
474 asyncDoProc :: FunPtr (Ptr a -> IO Int) -> Ptr a -> IO Int
475 asyncDoProc (FunPtr proc) (Ptr param) =
476 -- the 'length' value is ignored; simplifies implementation of
477 -- the async*# primops to have them all return the same result.
478 IO $ \s -> case asyncDoProc# proc param s of
479 (# s, len#, err# #) -> (# s, I# err# #)
481 -- to aid the use of these primops by the IO Handle implementation,
482 -- provide the following convenience funs:
484 -- this better be a pinned byte array!
485 asyncReadBA :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int,Int)
486 asyncReadBA fd isSock len off bufB =
487 asyncRead fd isSock len ((Ptr (byteArrayContents# (unsafeCoerce# bufB))) `plusPtr` off)
489 asyncWriteBA :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int,Int)
490 asyncWriteBA fd isSock len off bufB =
491 asyncWrite fd isSock len ((Ptr (byteArrayContents# (unsafeCoerce# bufB))) `plusPtr` off)
495 -- -----------------------------------------------------------------------------
498 -- | Block the current thread until data is available to read on the
499 -- given file descriptor (GHC only).
500 threadWaitRead :: Fd -> IO ()
502 #ifndef mingw32_HOST_OS
503 | threaded = waitForReadEvent fd
505 | otherwise = IO $ \s ->
506 case fromIntegral fd of { I# fd# ->
507 case waitRead# fd# s of { s -> (# s, () #)
510 -- | Block the current thread until data can be written to the
511 -- given file descriptor (GHC only).
512 threadWaitWrite :: Fd -> IO ()
514 #ifndef mingw32_HOST_OS
515 | threaded = waitForWriteEvent fd
517 | otherwise = IO $ \s ->
518 case fromIntegral fd of { I# fd# ->
519 case waitWrite# fd# s of { s -> (# s, () #)
522 -- | Suspends the current thread for a given number of microseconds
525 -- Note that the resolution used by the Haskell runtime system's
526 -- internal timer is 1\/50 second, and 'threadDelay' will round its
527 -- argument up to the nearest multiple of this resolution.
529 -- There is no guarantee that the thread will be rescheduled promptly
530 -- when the delay has expired, but the thread will never continue to
531 -- run /earlier/ than specified.
533 threadDelay :: Int -> IO ()
535 #ifndef mingw32_HOST_OS
536 | threaded = waitForDelayEvent time
538 | threaded = c_Sleep (fromIntegral (time `quot` 1000))
540 | otherwise = IO $ \s ->
541 case fromIntegral time of { I# time# ->
542 case delay# time# s of { s -> (# s, () #)
546 #ifndef mingw32_HOST_OS
547 | threaded = waitForDelayEventSTM usecs
548 | otherwise = error "registerDelay: requires -threaded"
550 = error "registerDelay: not currently supported on Windows"
553 -- On Windows, we just make a safe call to 'Sleep' to implement threadDelay.
554 #ifdef mingw32_HOST_OS
555 foreign import stdcall safe "Sleep" c_Sleep :: CInt -> IO ()
558 foreign import ccall unsafe "rtsSupportsBoundThreads" threaded :: Bool
560 -- ----------------------------------------------------------------------------
561 -- Threaded RTS implementation of threadWaitRead, threadWaitWrite, threadDelay
563 -- In the threaded RTS, we employ a single IO Manager thread to wait
564 -- for all outstanding IO requests (threadWaitRead,threadWaitWrite)
565 -- and delays (threadDelay).
567 -- We can do this because in the threaded RTS the IO Manager can make
568 -- a non-blocking call to select(), so we don't have to do select() in
569 -- the scheduler as we have to in the non-threaded RTS. We get performance
570 -- benefits from doing it this way, because we only have to restart the select()
571 -- when a new request arrives, rather than doing one select() each time
572 -- around the scheduler loop. Furthermore, the scheduler can be simplified
573 -- by not having to check for completed IO requests.
575 -- Issues, possible problems:
577 -- - we might want bound threads to just do the blocking
578 -- operation rather than communicating with the IO manager
579 -- thread. This would prevent simgle-threaded programs which do
580 -- IO from requiring multiple OS threads. However, it would also
581 -- prevent bound threads waiting on IO from being killed or sent
584 -- - Apprently exec() doesn't work on Linux in a multithreaded program.
585 -- I couldn't repeat this.
587 -- - How do we handle signal delivery in the multithreaded RTS?
589 -- - forkProcess will kill the IO manager thread. Let's just
590 -- hope we don't need to do any blocking IO between fork & exec.
592 #ifndef mingw32_HOST_OS
595 = Read {-# UNPACK #-} !Fd {-# UNPACK #-} !(MVar ())
596 | Write {-# UNPACK #-} !Fd {-# UNPACK #-} !(MVar ())
599 = Delay {-# UNPACK #-} !Int {-# UNPACK #-} !(MVar ())
600 | DelaySTM {-# UNPACK #-} !Int {-# UNPACK #-} !(TVar Bool)
602 pendingEvents :: IORef [IOReq]
603 pendingDelays :: IORef [DelayReq]
604 -- could use a strict list or array here
605 {-# NOINLINE pendingEvents #-}
606 {-# NOINLINE pendingDelays #-}
607 (pendingEvents,pendingDelays) = unsafePerformIO $ do
612 -- the first time we schedule an IO request, the service thread
613 -- will be created (cool, huh?)
615 ensureIOManagerIsRunning :: IO ()
616 ensureIOManagerIsRunning
617 | threaded = seq pendingEvents $ return ()
618 | otherwise = return ()
620 startIOManagerThread :: IO ()
621 startIOManagerThread = do
622 allocaArray 2 $ \fds -> do
623 throwErrnoIfMinus1 "startIOManagerThread" (c_pipe fds)
624 rd_end <- peekElemOff fds 0
625 wr_end <- peekElemOff fds 1
626 writeIORef stick (fromIntegral wr_end)
627 c_setIOManagerPipe wr_end
629 allocaBytes sizeofFdSet $ \readfds -> do
630 allocaBytes sizeofFdSet $ \writefds -> do
631 allocaBytes sizeofTimeVal $ \timeval -> do
632 service_loop (fromIntegral rd_end) readfds writefds timeval [] []
636 :: Fd -- listen to this for wakeup calls
643 service_loop wakeup readfds writefds ptimeval old_reqs old_delays = do
645 -- pick up new IO requests
646 new_reqs <- atomicModifyIORef pendingEvents (\a -> ([],a))
647 let reqs = new_reqs ++ old_reqs
649 -- pick up new delay requests
650 new_delays <- atomicModifyIORef pendingDelays (\a -> ([],a))
651 let delays = foldr insertDelay old_delays new_delays
653 -- build the FDSets for select()
657 maxfd <- buildFdSets 0 readfds writefds reqs
659 -- perform the select()
660 let do_select delays = do
661 -- check the current time and wake up any thread in
662 -- threadDelay whose timeout has expired. Also find the
663 -- timeout value for the select() call.
665 (delays', timeout) <- getDelay now ptimeval delays
667 res <- c_select ((max wakeup maxfd)+1) readfds writefds
673 then do_select delays'
674 else return (res,delays')
678 (res,delays') <- do_select delays
679 -- ToDo: check result
681 b <- fdIsSet wakeup readfds
684 else alloca $ \p -> do
685 c_read (fromIntegral wakeup) p 1; return ()
689 else do handler_tbl <- peek handlers
690 sp <- peekElemOff handler_tbl (fromIntegral s)
691 forkIO (do io <- deRefStablePtr sp; io)
695 putMVar prodding False
697 reqs' <- completeRequests reqs readfds writefds []
698 service_loop wakeup readfds writefds ptimeval reqs' delays'
701 {-# NOINLINE stick #-}
702 stick = unsafePerformIO (newIORef 0)
704 prodding :: MVar Bool
705 {-# NOINLINE prodding #-}
706 prodding = unsafePerformIO (newMVar False)
708 prodServiceThread :: IO ()
709 prodServiceThread = do
710 b <- takeMVar prodding
712 then do fd <- readIORef stick
713 with 0xff $ \pbuf -> do c_write (fromIntegral fd) pbuf 1; return ()
715 putMVar prodding True
717 foreign import ccall "&signal_handlers" handlers :: Ptr (Ptr (StablePtr (IO ())))
719 foreign import ccall "setIOManagerPipe"
720 c_setIOManagerPipe :: CInt -> IO ()
722 -- -----------------------------------------------------------------------------
725 buildFdSets maxfd readfds writefds [] = return maxfd
726 buildFdSets maxfd readfds writefds (Read fd m : reqs)
727 | fd >= fD_SETSIZE = error "buildFdSets: file descriptor out of range"
730 buildFdSets (max maxfd fd) readfds writefds reqs
731 buildFdSets maxfd readfds writefds (Write fd m : reqs)
732 | fd >= fD_SETSIZE = error "buildFdSets: file descriptor out of range"
735 buildFdSets (max maxfd fd) readfds writefds reqs
737 completeRequests [] _ _ reqs' = return reqs'
738 completeRequests (Read fd m : reqs) readfds writefds reqs' = do
739 b <- fdIsSet fd readfds
741 then do putMVar m (); completeRequests reqs readfds writefds reqs'
742 else completeRequests reqs readfds writefds (Read fd m : reqs')
743 completeRequests (Write fd m : reqs) readfds writefds reqs' = do
744 b <- fdIsSet fd writefds
746 then do putMVar m (); completeRequests reqs readfds writefds reqs'
747 else completeRequests reqs readfds writefds (Write fd m : reqs')
749 waitForReadEvent :: Fd -> IO ()
750 waitForReadEvent fd = do
752 atomicModifyIORef pendingEvents (\xs -> (Read fd m : xs, ()))
756 waitForWriteEvent :: Fd -> IO ()
757 waitForWriteEvent fd = do
759 atomicModifyIORef pendingEvents (\xs -> (Write fd m : xs, ()))
763 -- XXX: move into GHC.IOBase from Data.IORef?
764 atomicModifyIORef :: IORef a -> (a -> (a,b)) -> IO b
765 atomicModifyIORef (IORef (STRef r#)) f = IO $ \s -> atomicModifyMutVar# r# f s
767 -- -----------------------------------------------------------------------------
770 waitForDelayEvent :: Int -> IO ()
771 waitForDelayEvent usecs = do
774 let target = now + usecs `quot` tick_usecs
775 atomicModifyIORef pendingDelays (\xs -> (Delay target m : xs, ()))
779 -- Delays for use in STM
780 waitForDelayEventSTM :: Int -> IO (TVar Bool)
781 waitForDelayEventSTM usecs = do
782 t <- atomically $ newTVar False
784 let target = now + usecs `quot` tick_usecs
785 atomicModifyIORef pendingDelays (\xs -> (DelaySTM target t : xs, ()))
789 -- Walk the queue of pending delays, waking up any that have passed
790 -- and return the smallest delay to wait for. The queue of pending
791 -- delays is kept ordered.
792 getDelay :: Ticks -> Ptr CTimeVal -> [DelayReq] -> IO ([DelayReq], Ptr CTimeVal)
793 getDelay now ptimeval [] = return ([],nullPtr)
794 getDelay now ptimeval all@(d : rest)
796 Delay time m | now >= time -> do
798 getDelay now ptimeval rest
799 DelaySTM time t | now >= time -> do
800 atomically $ writeTVar t True
801 getDelay now ptimeval rest
803 setTimevalTicks ptimeval (delayTime d - now)
804 return (all,ptimeval)
806 insertDelay :: DelayReq -> [DelayReq] -> [DelayReq]
807 insertDelay d [] = [d]
808 insertDelay d1 ds@(d2 : rest)
809 | delayTime d1 <= delayTime d2 = d1 : ds
810 | otherwise = d2 : insertDelay d1 rest
812 delayTime (Delay t _) = t
813 delayTime (DelaySTM t _) = t
816 tick_freq = 50 :: Ticks -- accuracy of threadDelay (ticks per sec)
817 tick_usecs = 1000000 `quot` tick_freq :: Int
819 newtype CTimeVal = CTimeVal ()
821 foreign import ccall unsafe "sizeofTimeVal"
824 foreign import ccall unsafe "getTicksOfDay"
825 getTicksOfDay :: IO Ticks
827 foreign import ccall unsafe "setTimevalTicks"
828 setTimevalTicks :: Ptr CTimeVal -> Ticks -> IO ()
830 -- ----------------------------------------------------------------------------
831 -- select() interface
833 -- ToDo: move to System.Posix.Internals?
835 newtype CFdSet = CFdSet ()
837 foreign import ccall safe "select"
838 c_select :: Fd -> Ptr CFdSet -> Ptr CFdSet -> Ptr CFdSet -> Ptr CTimeVal
841 foreign import ccall unsafe "hsFD_SETSIZE"
844 foreign import ccall unsafe "hsFD_CLR"
845 fdClr :: Fd -> Ptr CFdSet -> IO ()
847 foreign import ccall unsafe "hsFD_ISSET"
848 fdIsSet :: Fd -> Ptr CFdSet -> IO CInt
850 foreign import ccall unsafe "hsFD_SET"
851 fdSet :: Fd -> Ptr CFdSet -> IO ()
853 foreign import ccall unsafe "hsFD_ZERO"
854 fdZero :: Ptr CFdSet -> IO ()
856 foreign import ccall unsafe "sizeof_fd_set"