2 {-# OPTIONS -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 #include "ghcconfig.h"
21 -- Forking and suchlike
22 , myThreadId -- :: IO ThreadId
23 , killThread -- :: ThreadId -> IO ()
24 , throwTo -- :: ThreadId -> Exception -> IO ()
25 , par -- :: a -> b -> b
26 , pseq -- :: a -> b -> b
28 , labelThread -- :: ThreadId -> String -> IO ()
31 , threadDelay -- :: Int -> IO ()
32 , threadWaitRead -- :: Int -> IO ()
33 , threadWaitWrite -- :: Int -> IO ()
37 , newMVar -- :: a -> IO (MVar a)
38 , newEmptyMVar -- :: IO (MVar a)
39 , takeMVar -- :: MVar a -> IO a
40 , putMVar -- :: MVar a -> a -> IO ()
41 , tryTakeMVar -- :: MVar a -> IO (Maybe a)
42 , tryPutMVar -- :: MVar a -> a -> IO Bool
43 , isEmptyMVar -- :: MVar a -> IO Bool
44 , addMVarFinalizer -- :: MVar a -> IO () -> IO ()
46 #ifdef mingw32_TARGET_OS
47 , asyncRead -- :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
48 , asyncWrite -- :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
49 , asyncDoProc -- :: FunPtr (Ptr a -> IO Int) -> Ptr a -> IO Int
51 , asyncReadBA -- :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int, Int)
52 , asyncWriteBA -- :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int, Int)
56 import System.Posix.Types
57 import System.Posix.Internals
65 import GHC.Num ( Num(..) )
66 import GHC.Real ( fromIntegral, quot )
67 import GHC.Base ( Int(..) )
68 import GHC.Exception ( Exception(..), AsyncException(..) )
69 import GHC.Pack ( packCString# )
70 import GHC.Ptr ( Ptr(..), plusPtr, FunPtr(..) )
73 infixr 0 `par`, `pseq`
76 %************************************************************************
78 \subsection{@ThreadId@, @par@, and @fork@}
80 %************************************************************************
83 data ThreadId = ThreadId ThreadId#
84 -- ToDo: data ThreadId = ThreadId (Weak ThreadId#)
85 -- But since ThreadId# is unlifted, the Weak type must use open
88 A 'ThreadId' is an abstract type representing a handle to a thread.
89 'ThreadId' is an instance of 'Eq', 'Ord' and 'Show', where
90 the 'Ord' instance implements an arbitrary total ordering over
91 'ThreadId's. The 'Show' instance lets you convert an arbitrary-valued
92 'ThreadId' to string form; showing a 'ThreadId' value is occasionally
93 useful when debugging or diagnosing the behaviour of a concurrent
96 /Note/: in GHC, if you have a 'ThreadId', you essentially have
97 a pointer to the thread itself. This means the thread itself can\'t be
98 garbage collected until you drop the 'ThreadId'.
99 This misfeature will hopefully be corrected at a later date.
101 /Note/: Hugs does not provide any operations on other threads;
102 it defines 'ThreadId' as a synonym for ().
105 --forkIO has now been hoisted out into the Concurrent library.
107 {- | 'killThread' terminates the given thread (GHC only).
108 Any work already done by the thread isn\'t
109 lost: the computation is suspended until required by another thread.
110 The memory used by the thread will be garbage collected if it isn\'t
111 referenced from anywhere. The 'killThread' function is defined in
114 > killThread tid = throwTo tid (AsyncException ThreadKilled)
117 killThread :: ThreadId -> IO ()
118 killThread tid = throwTo tid (AsyncException ThreadKilled)
120 {- | 'throwTo' raises an arbitrary exception in the target thread (GHC only).
122 'throwTo' does not return until the exception has been raised in the
123 target thread. The calling thread can thus be certain that the target
124 thread has received the exception. This is a useful property to know
125 when dealing with race conditions: eg. if there are two threads that
126 can kill each other, it is guaranteed that only one of the threads
127 will get to kill the other. -}
128 throwTo :: ThreadId -> Exception -> IO ()
129 throwTo (ThreadId id) ex = IO $ \ s ->
130 case (killThread# id ex s) of s1 -> (# s1, () #)
132 -- | Returns the 'ThreadId' of the calling thread (GHC only).
133 myThreadId :: IO ThreadId
134 myThreadId = IO $ \s ->
135 case (myThreadId# s) of (# s1, id #) -> (# s1, ThreadId id #)
138 -- |The 'yield' action allows (forces, in a co-operative multitasking
139 -- implementation) a context-switch to any other currently runnable
140 -- threads (if any), and is occasionally useful when implementing
141 -- concurrency abstractions.
144 case (yield# s) of s1 -> (# s1, () #)
146 {- | 'labelThread' stores a string as identifier for this thread if
147 you built a RTS with debugging support. This identifier will be used in
148 the debugging output to make distinction of different threads easier
149 (otherwise you only have the thread state object\'s address in the heap).
151 Other applications like the graphical Concurrent Haskell Debugger
152 (<http://www.informatik.uni-kiel.de/~fhu/chd/>) may choose to overload
153 'labelThread' for their purposes as well.
156 labelThread :: ThreadId -> String -> IO ()
157 labelThread (ThreadId t) str = IO $ \ s ->
158 let ps = packCString# str
159 adr = byteArrayContents# ps in
160 case (labelThread# t adr s) of s1 -> (# s1, () #)
162 -- Nota Bene: 'pseq' used to be 'seq'
163 -- but 'seq' is now defined in PrelGHC
165 -- "pseq" is defined a bit weirdly (see below)
167 -- The reason for the strange "lazy" call is that
168 -- it fools the compiler into thinking that pseq and par are non-strict in
169 -- their second argument (even if it inlines pseq at the call site).
170 -- If it thinks pseq is strict in "y", then it often evaluates
171 -- "y" before "x", which is totally wrong.
175 pseq x y = x `seq` lazy y
179 par x y = case (par# x) of { _ -> lazy y }
182 %************************************************************************
184 \subsection[mvars]{M-Structures}
186 %************************************************************************
188 M-Vars are rendezvous points for concurrent threads. They begin
189 empty, and any attempt to read an empty M-Var blocks. When an M-Var
190 is written, a single blocked thread may be freed. Reading an M-Var
191 toggles its state from full back to empty. Therefore, any value
192 written to an M-Var may only be read once. Multiple reads and writes
193 are allowed, but there must be at least one read between any two
197 --Defined in IOBase to avoid cycle: data MVar a = MVar (SynchVar# RealWorld a)
199 -- |Create an 'MVar' which is initially empty.
200 newEmptyMVar :: IO (MVar a)
201 newEmptyMVar = IO $ \ s# ->
203 (# s2#, svar# #) -> (# s2#, MVar svar# #)
205 -- |Create an 'MVar' which contains the supplied value.
206 newMVar :: a -> IO (MVar a)
208 newEmptyMVar >>= \ mvar ->
209 putMVar mvar value >>
212 -- |Return the contents of the 'MVar'. If the 'MVar' is currently
213 -- empty, 'takeMVar' will wait until it is full. After a 'takeMVar',
214 -- the 'MVar' is left empty.
216 -- If several threads are competing to take the same 'MVar', one is chosen
217 -- to continue at random when the 'MVar' becomes full.
218 takeMVar :: MVar a -> IO a
219 takeMVar (MVar mvar#) = IO $ \ s# -> takeMVar# mvar# s#
221 -- |Put a value into an 'MVar'. If the 'MVar' is currently full,
222 -- 'putMVar' will wait until it becomes empty.
224 -- If several threads are competing to fill the same 'MVar', one is
225 -- chosen to continue at random when the 'MVar' becomes empty.
226 putMVar :: MVar a -> a -> IO ()
227 putMVar (MVar mvar#) x = IO $ \ s# ->
228 case putMVar# mvar# x s# of
231 -- |A non-blocking version of 'takeMVar'. The 'tryTakeMVar' function
232 -- returns immediately, with 'Nothing' if the 'MVar' was empty, or
233 -- @'Just' a@ if the 'MVar' was full with contents @a@. After 'tryTakeMVar',
234 -- the 'MVar' is left empty.
235 tryTakeMVar :: MVar a -> IO (Maybe a)
236 tryTakeMVar (MVar m) = IO $ \ s ->
237 case tryTakeMVar# m s of
238 (# s, 0#, _ #) -> (# s, Nothing #) -- MVar is empty
239 (# s, _, a #) -> (# s, Just a #) -- MVar is full
241 -- |A non-blocking version of 'putMVar'. The 'tryPutMVar' function
242 -- attempts to put the value @a@ into the 'MVar', returning 'True' if
243 -- it was successful, or 'False' otherwise.
244 tryPutMVar :: MVar a -> a -> IO Bool
245 tryPutMVar (MVar mvar#) x = IO $ \ s# ->
246 case tryPutMVar# mvar# x s# of
247 (# s, 0# #) -> (# s, False #)
248 (# s, _ #) -> (# s, True #)
250 -- |Check whether a given 'MVar' is empty.
252 -- Notice that the boolean value returned is just a snapshot of
253 -- the state of the MVar. By the time you get to react on its result,
254 -- the MVar may have been filled (or emptied) - so be extremely
255 -- careful when using this operation. Use 'tryTakeMVar' instead if possible.
256 isEmptyMVar :: MVar a -> IO Bool
257 isEmptyMVar (MVar mv#) = IO $ \ s# ->
258 case isEmptyMVar# mv# s# of
259 (# s2#, flg #) -> (# s2#, not (flg ==# 0#) #)
261 -- |Add a finalizer to an 'MVar' (GHC only). See "Foreign.ForeignPtr" and
262 -- "System.Mem.Weak" for more about finalizers.
263 addMVarFinalizer :: MVar a -> IO () -> IO ()
264 addMVarFinalizer (MVar m) finalizer =
265 IO $ \s -> case mkWeak# m () finalizer s of { (# s1, w #) -> (# s1, () #) }
269 %************************************************************************
271 \subsection{Thread waiting}
273 %************************************************************************
276 #ifdef mingw32_TARGET_OS
278 -- Note: threadDelay, threadWaitRead and threadWaitWrite aren't really functional
279 -- on Win32, but left in there because lib code (still) uses them (the manner
280 -- in which they're used doesn't cause problems on a Win32 platform though.)
282 asyncRead :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
283 asyncRead (I# fd) (I# isSock) (I# len) (Ptr buf) =
284 IO $ \s -> case asyncRead# fd isSock len buf s of
285 (# s, len#, err# #) -> (# s, (I# len#, I# err#) #)
287 asyncWrite :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
288 asyncWrite (I# fd) (I# isSock) (I# len) (Ptr buf) =
289 IO $ \s -> case asyncWrite# fd isSock len buf s of
290 (# s, len#, err# #) -> (# s, (I# len#, I# err#) #)
292 asyncDoProc :: FunPtr (Ptr a -> IO Int) -> Ptr a -> IO Int
293 asyncDoProc (FunPtr proc) (Ptr param) =
294 -- the 'length' value is ignored; simplifies implementation of
295 -- the async*# primops to have them all return the same result.
296 IO $ \s -> case asyncDoProc# proc param s of
297 (# s, len#, err# #) -> (# s, I# err# #)
299 -- to aid the use of these primops by the IO Handle implementation,
300 -- provide the following convenience funs:
302 -- this better be a pinned byte array!
303 asyncReadBA :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int,Int)
304 asyncReadBA fd isSock len off bufB =
305 asyncRead fd isSock len ((Ptr (byteArrayContents# (unsafeCoerce# bufB))) `plusPtr` off)
307 asyncWriteBA :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int,Int)
308 asyncWriteBA fd isSock len off bufB =
309 asyncWrite fd isSock len ((Ptr (byteArrayContents# (unsafeCoerce# bufB))) `plusPtr` off)
313 -- -----------------------------------------------------------------------------
316 -- | Block the current thread until data is available to read on the
317 -- given file descriptor (GHC only).
318 threadWaitRead :: Fd -> IO ()
320 #ifndef mingw32_TARGET_OS
321 | threaded = waitForReadEvent fd
323 | otherwise = IO $ \s ->
324 case fromIntegral fd of { I# fd# ->
325 case waitRead# fd# s of { s -> (# s, () #)
328 -- | Block the current thread until data can be written to the
329 -- given file descriptor (GHC only).
330 threadWaitWrite :: Fd -> IO ()
332 #ifndef mingw32_TARGET_OS
333 | threaded = waitForWriteEvent fd
335 | otherwise = IO $ \s ->
336 case fromIntegral fd of { I# fd# ->
337 case waitWrite# fd# s of { s -> (# s, () #)
340 -- | Suspends the current thread for a given number of microseconds
343 -- Note that the resolution used by the Haskell runtime system's
344 -- internal timer is 1\/50 second, and 'threadDelay' will round its
345 -- argument up to the nearest multiple of this resolution.
347 -- There is no guarantee that the thread will be rescheduled promptly
348 -- when the delay has expired, but the thread will never continue to
349 -- run /earlier/ than specified.
351 threadDelay :: Int -> IO ()
353 #ifndef mingw32_TARGET_OS
354 | threaded = waitForDelayEvent time
356 | threaded = c_Sleep (fromIntegral (time `quot` 1000))
358 | otherwise = IO $ \s ->
359 case fromIntegral time of { I# time# ->
360 case delay# time# s of { s -> (# s, () #)
363 -- On Windows, we just make a safe call to 'Sleep' to implement threadDelay.
364 #ifdef mingw32_TARGET_OS
365 foreign import ccall safe "Sleep" c_Sleep :: CInt -> IO ()
368 foreign import ccall unsafe "rtsSupportsBoundThreads" threaded :: Bool
370 -- ----------------------------------------------------------------------------
371 -- Threaded RTS implementation of threadWaitRead, threadWaitWrite, threadDelay
373 -- In the threaded RTS, we employ a single IO Manager thread to wait
374 -- for all outstanding IO requests (threadWaitRead,threadWaitWrite)
375 -- and delays (threadDelay).
377 -- We can do this because in the threaded RTS the IO Manager can make
378 -- a non-blocking call to select(), so we don't have to do select() in
379 -- the scheduler as we have to in the non-threaded RTS. We get performance
380 -- benefits from doing it this way, because we only have to restart the select()
381 -- when a new request arrives, rather than doing one select() each time
382 -- around the scheduler loop. Furthermore, the scheduler can be simplified
383 -- by not having to check for completed IO requests.
385 -- Issues, possible problems:
387 -- - we might want bound threads to just do the blocking
388 -- operation rather than communicating with the IO manager
389 -- thread. This would prevent simgle-threaded programs which do
390 -- IO from requiring multiple OS threads. However, it would also
391 -- prevent bound threads waiting on IO from being killed or sent
394 -- - Apprently exec() doesn't work on Linux in a multithreaded program.
395 -- I couldn't repeat this.
397 -- - How do we handle signal delivery in the multithreaded RTS?
399 -- - forkProcess will kill the IO manager thread. Let's just
400 -- hope we don't need to do any blocking IO between fork & exec.
402 #ifndef mingw32_TARGET_OS
405 = Read {-# UNPACK #-} !Fd {-# UNPACK #-} !(MVar ())
406 | Write {-# UNPACK #-} !Fd {-# UNPACK #-} !(MVar ())
409 = Delay {-# UNPACK #-} !Int {-# UNPACK #-} !(MVar ())
411 pendingEvents :: IORef [IOReq]
412 pendingDelays :: IORef [DelayReq]
413 -- could use a strict list or array here
414 {-# NOINLINE pendingEvents #-}
415 {-# NOINLINE pendingDelays #-}
416 (pendingEvents,pendingDelays) = unsafePerformIO $ do
421 -- the first time we schedule an IO request, the service thread
422 -- will be created (cool, huh?)
424 startIOServiceThread :: IO ()
425 startIOServiceThread = do
426 allocaArray 2 $ \fds -> do
427 throwErrnoIfMinus1 "startIOServiceThread" (c_pipe fds)
428 rd_end <- peekElemOff fds 0
429 wr_end <- peekElemOff fds 1
430 writeIORef stick (fromIntegral wr_end)
432 allocaBytes sizeofFdSet $ \readfds -> do
433 allocaBytes sizeofFdSet $ \writefds -> do
434 allocaBytes sizeofTimeVal $ \timeval -> do
435 service_loop (fromIntegral rd_end) readfds writefds timeval [] []
438 -- XXX: move real forkIO here from Control.Concurrent?
439 quickForkIO action = IO $ \s ->
440 case (fork# action s) of (# s1, id #) -> (# s1, ThreadId id #)
443 :: Fd -- listen to this for wakeup calls
450 service_loop wakeup readfds writefds ptimeval old_reqs old_delays = do
452 -- pick up new IO requests
453 new_reqs <- atomicModifyIORef pendingEvents (\a -> ([],a))
454 let reqs = new_reqs ++ old_reqs
456 -- pick up new delay requests
457 new_delays <- atomicModifyIORef pendingDelays (\a -> ([],a))
458 let delays = foldr insertDelay old_delays new_delays
460 -- build the FDSets for select()
464 maxfd <- buildFdSets 0 readfds writefds reqs
466 -- check the current time and wake up any thread in threadDelay whose
467 -- timeout has expired. Also find the timeout value for the select() call.
469 (delays', timeout) <- getDelay now ptimeval delays
471 -- perform the select()
473 res <- c_select ((max wakeup maxfd)+1) readfds writefds
484 -- ToDo: check result
486 old <- atomicModifyIORef prodding (\old -> (False,old))
488 then alloca $ \p -> do c_read (fromIntegral wakeup) p 1; return ()
491 reqs' <- completeRequests reqs readfds writefds []
492 service_loop wakeup readfds writefds ptimeval reqs' delays'
495 {-# NOINLINE stick #-}
496 stick = unsafePerformIO (newIORef 0)
498 prodding :: IORef Bool
499 {-# NOINLINE prodding #-}
500 prodding = unsafePerformIO (newIORef False)
502 prodServiceThread :: IO ()
503 prodServiceThread = do
504 b <- atomicModifyIORef prodding (\old -> (True,old)) -- compare & swap!
507 fd <- readIORef stick
508 with 42 $ \pbuf -> do c_write (fromIntegral fd) pbuf 1; return ()
512 -- -----------------------------------------------------------------------------
515 buildFdSets maxfd readfds writefds [] = return maxfd
516 buildFdSets maxfd readfds writefds (Read fd m : reqs) = do
518 buildFdSets (max maxfd fd) readfds writefds reqs
519 buildFdSets maxfd readfds writefds (Write fd m : reqs) = do
521 buildFdSets (max maxfd fd) readfds writefds reqs
523 completeRequests [] _ _ reqs' = return reqs'
524 completeRequests (Read fd m : reqs) readfds writefds reqs' = do
525 b <- fdIsSet fd readfds
527 then do putMVar m (); completeRequests reqs readfds writefds reqs'
528 else completeRequests reqs readfds writefds (Read fd m : reqs')
529 completeRequests (Write fd m : reqs) readfds writefds reqs' = do
530 b <- fdIsSet fd writefds
532 then do putMVar m (); completeRequests reqs readfds writefds reqs'
533 else completeRequests reqs readfds writefds (Write fd m : reqs')
535 waitForReadEvent :: Fd -> IO ()
536 waitForReadEvent fd = do
538 atomicModifyIORef pendingEvents (\xs -> (Read fd m : xs, ()))
542 waitForWriteEvent :: Fd -> IO ()
543 waitForWriteEvent fd = do
545 atomicModifyIORef pendingEvents (\xs -> (Write fd m : xs, ()))
549 -- XXX: move into GHC.IOBase from Data.IORef?
550 atomicModifyIORef :: IORef a -> (a -> (a,b)) -> IO b
551 atomicModifyIORef (IORef (STRef r#)) f = IO $ \s -> atomicModifyMutVar# r# f s
553 -- -----------------------------------------------------------------------------
556 waitForDelayEvent :: Int -> IO ()
557 waitForDelayEvent usecs = do
560 let target = now + usecs `quot` tick_usecs
561 atomicModifyIORef pendingDelays (\xs -> (Delay target m : xs, ()))
565 -- Walk the queue of pending delays, waking up any that have passed
566 -- and return the smallest delay to wait for. The queue of pending
567 -- delays is kept ordered.
568 getDelay :: Ticks -> Ptr CTimeVal -> [DelayReq] -> IO ([DelayReq], Ptr CTimeVal)
569 getDelay now ptimeval [] = return ([],nullPtr)
570 getDelay now ptimeval all@(Delay time m : rest)
573 getDelay now ptimeval rest
575 setTimevalTicks ptimeval (time - now)
576 return (all,ptimeval)
578 insertDelay :: DelayReq -> [DelayReq] -> [DelayReq]
579 insertDelay d@(Delay time m) [] = [d]
580 insertDelay d1@(Delay time m) ds@(d2@(Delay time' m') : rest)
581 | time <= time' = d1 : ds
582 | otherwise = d2 : insertDelay d1 rest
585 tick_freq = 50 :: Ticks -- accuracy of threadDelay (ticks per sec)
586 tick_usecs = 1000000 `quot` tick_freq :: Int
588 newtype CTimeVal = CTimeVal ()
590 foreign import ccall unsafe "sizeofTimeVal"
593 foreign import ccall unsafe "getTicksOfDay"
594 getTicksOfDay :: IO Ticks
596 foreign import ccall unsafe "setTimevalTicks"
597 setTimevalTicks :: Ptr CTimeVal -> Ticks -> IO ()
599 -- ----------------------------------------------------------------------------
600 -- select() interface
602 -- ToDo: move to System.Posix.Internals?
604 newtype CFdSet = CFdSet ()
606 foreign import ccall safe "select"
607 c_select :: Fd -> Ptr CFdSet -> Ptr CFdSet -> Ptr CFdSet -> Ptr CTimeVal
610 foreign import ccall unsafe "hsFD_CLR"
611 fdClr :: Fd -> Ptr CFdSet -> IO ()
613 foreign import ccall unsafe "hsFD_ISSET"
614 fdIsSet :: Fd -> Ptr CFdSet -> IO CInt
616 foreign import ccall unsafe "hsFD_SET"
617 fdSet :: Fd -> Ptr CFdSet -> IO ()
619 foreign import ccall unsafe "hsFD_ZERO"
620 fdZero :: Ptr CFdSet -> IO ()
622 foreign import ccall unsafe "sizeof_fd_set"