Add note about synhronous delivery of throwTo
[ghc-base.git] / GHC / Conc.lhs
1 \begin{code}
2 {-# OPTIONS_GHC -fno-implicit-prelude #-}
3 -----------------------------------------------------------------------------
4 -- |
5 -- Module      :  GHC.Conc
6 -- Copyright   :  (c) The University of Glasgow, 1994-2002
7 -- License     :  see libraries/base/LICENSE
8 -- 
9 -- Maintainer  :  cvs-ghc@haskell.org
10 -- Stability   :  internal
11 -- Portability :  non-portable (GHC extensions)
12 --
13 -- Basic concurrency stuff.
14 -- 
15 -----------------------------------------------------------------------------
16
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:
21
22 #include "Typeable.h"
23
24 -- #not-home
25 module GHC.Conc
26         ( ThreadId(..)
27
28         -- * Forking and suchlike
29         , forkIO        -- :: IO a -> IO ThreadId
30         , forkOnIO      -- :: Int -> IO a -> IO ThreadId
31         , childHandler  -- :: Exception -> IO ()
32         , myThreadId    -- :: IO ThreadId
33         , killThread    -- :: ThreadId -> IO ()
34         , throwTo       -- :: ThreadId -> Exception -> IO ()
35         , par           -- :: a -> b -> b
36         , pseq          -- :: a -> b -> b
37         , yield         -- :: IO ()
38         , labelThread   -- :: ThreadId -> String -> IO ()
39
40         -- * Waiting
41         , threadDelay           -- :: Int -> IO ()
42         , registerDelay         -- :: Int -> IO (TVar Bool)
43         , threadWaitRead        -- :: Int -> IO ()
44         , threadWaitWrite       -- :: Int -> IO ()
45
46         -- * MVars
47         , MVar          -- abstract
48         , newMVar       -- :: a -> IO (MVar a)
49         , newEmptyMVar  -- :: IO (MVar a)
50         , takeMVar      -- :: MVar a -> IO a
51         , putMVar       -- :: MVar a -> a -> IO ()
52         , tryTakeMVar   -- :: MVar a -> IO (Maybe a)
53         , tryPutMVar    -- :: MVar a -> a -> IO Bool
54         , isEmptyMVar   -- :: MVar a -> IO Bool
55         , addMVarFinalizer -- :: MVar a -> IO () -> IO ()
56
57         -- * TVars
58         , STM           -- abstract
59         , atomically    -- :: STM a -> IO a
60         , retry         -- :: STM a
61         , orElse        -- :: STM a -> STM a -> STM a
62         , catchSTM      -- :: STM a -> (Exception -> STM a) -> STM a
63         , alwaysSucceeds -- :: STM a -> STM ()
64         , always        -- :: STM Bool -> STM ()
65         , TVar          -- abstract
66         , newTVar       -- :: a -> STM (TVar a)
67         , newTVarIO     -- :: a -> STM (TVar a)
68         , readTVar      -- :: TVar a -> STM a
69         , writeTVar     -- :: a -> TVar a -> STM ()
70         , unsafeIOToSTM -- :: IO a -> STM a
71
72         -- * Miscellaneous
73 #ifdef mingw32_HOST_OS
74         , asyncRead     -- :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
75         , asyncWrite    -- :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
76         , asyncDoProc   -- :: FunPtr (Ptr a -> IO Int) -> Ptr a -> IO Int
77
78         , asyncReadBA   -- :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int, Int)
79         , asyncWriteBA  -- :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int, Int)
80 #endif
81
82         , ensureIOManagerIsRunning
83         ) where
84
85 import System.Posix.Types
86 #ifndef mingw32_HOST_OS
87 import System.Posix.Internals
88 #endif
89 import Foreign
90 import Foreign.C
91
92 #ifndef __HADDOCK__
93 import {-# SOURCE #-} GHC.TopHandler ( reportError, reportStackOverflow )
94 #endif
95
96 import Data.Maybe
97
98 import GHC.Base
99 import GHC.IOBase
100 import GHC.Num          ( Num(..) )
101 import GHC.Real         ( fromIntegral, quot )
102 #ifndef mingw32_HOST_OS
103 import GHC.Base         ( Int(..) )
104 #endif
105 import GHC.Exception    ( catchException, Exception(..), AsyncException(..) )
106 import GHC.Pack         ( packCString# )
107 import GHC.Ptr          ( Ptr(..), plusPtr, FunPtr(..) )
108 import GHC.STRef
109 import GHC.Show         ( Show(..), showString )
110 import Data.Typeable
111
112 infixr 0 `par`, `pseq`
113 \end{code}
114
115 %************************************************************************
116 %*                                                                      *
117 \subsection{@ThreadId@, @par@, and @fork@}
118 %*                                                                      *
119 %************************************************************************
120
121 \begin{code}
122 data ThreadId = ThreadId ThreadId# deriving( Typeable )
123 -- ToDo: data ThreadId = ThreadId (Weak ThreadId#)
124 -- But since ThreadId# is unlifted, the Weak type must use open
125 -- type variables.
126 {- ^
127 A 'ThreadId' is an abstract type representing a handle to a thread.
128 'ThreadId' is an instance of 'Eq', 'Ord' and 'Show', where
129 the 'Ord' instance implements an arbitrary total ordering over
130 'ThreadId's. The 'Show' instance lets you convert an arbitrary-valued
131 'ThreadId' to string form; showing a 'ThreadId' value is occasionally
132 useful when debugging or diagnosing the behaviour of a concurrent
133 program.
134
135 /Note/: in GHC, if you have a 'ThreadId', you essentially have
136 a pointer to the thread itself.  This means the thread itself can\'t be
137 garbage collected until you drop the 'ThreadId'.
138 This misfeature will hopefully be corrected at a later date.
139
140 /Note/: Hugs does not provide any operations on other threads;
141 it defines 'ThreadId' as a synonym for ().
142 -}
143
144 instance Show ThreadId where
145    showsPrec d t = 
146         showString "ThreadId " . 
147         showsPrec d (getThreadId (id2TSO t))
148
149 foreign import ccall unsafe "rts_getThreadId" getThreadId :: ThreadId# -> Int
150
151 id2TSO :: ThreadId -> ThreadId#
152 id2TSO (ThreadId t) = t
153
154 foreign import ccall unsafe "cmp_thread" cmp_thread :: ThreadId# -> ThreadId# -> CInt
155 -- Returns -1, 0, 1
156
157 cmpThread :: ThreadId -> ThreadId -> Ordering
158 cmpThread t1 t2 = 
159    case cmp_thread (id2TSO t1) (id2TSO t2) of
160       -1 -> LT
161       0  -> EQ
162       _  -> GT -- must be 1
163
164 instance Eq ThreadId where
165    t1 == t2 = 
166       case t1 `cmpThread` t2 of
167          EQ -> True
168          _  -> False
169
170 instance Ord ThreadId where
171    compare = cmpThread
172
173 {- |
174 This sparks off a new thread to run the 'IO' computation passed as the
175 first argument, and returns the 'ThreadId' of the newly created
176 thread.
177
178 The new thread will be a lightweight thread; if you want to use a foreign
179 library that uses thread-local storage, use 'forkOS' instead.
180 -}
181 forkIO :: IO () -> IO ThreadId
182 forkIO action = IO $ \ s -> 
183    case (fork# action_plus s) of (# s1, id #) -> (# s1, ThreadId id #)
184  where
185   action_plus = catchException action childHandler
186
187 forkOnIO :: Int -> IO () -> IO ThreadId
188 forkOnIO (I# cpu) action = IO $ \ s -> 
189    case (forkOn# cpu action_plus s) of (# s1, id #) -> (# s1, ThreadId id #)
190  where
191   action_plus = catchException action childHandler
192
193 childHandler :: Exception -> IO ()
194 childHandler err = catchException (real_handler err) childHandler
195
196 real_handler :: Exception -> IO ()
197 real_handler ex =
198   case ex of
199         -- ignore thread GC and killThread exceptions:
200         BlockedOnDeadMVar            -> return ()
201         BlockedIndefinitely          -> return ()
202         AsyncException ThreadKilled  -> return ()
203
204         -- report all others:
205         AsyncException StackOverflow -> reportStackOverflow
206         other       -> reportError other
207
208 {- | 'killThread' terminates the given thread (GHC only).
209 Any work already done by the thread isn\'t
210 lost: the computation is suspended until required by another thread.
211 The memory used by the thread will be garbage collected if it isn\'t
212 referenced from anywhere.  The 'killThread' function is defined in
213 terms of 'throwTo':
214
215 > killThread tid = throwTo tid (AsyncException ThreadKilled)
216
217 -}
218 killThread :: ThreadId -> IO ()
219 killThread tid = throwTo tid (AsyncException ThreadKilled)
220
221 {- | 'throwTo' raises an arbitrary exception in the target thread (GHC only).
222
223 'throwTo' does not return until the exception has been raised in the
224 target thread. 
225 The calling thread can thus be certain that the target
226 thread has received the exception.  This is a useful property to know
227 when dealing with race conditions: eg. if there are two threads that
228 can kill each other, it is guaranteed that only one of the threads
229 will get to kill the other.
230
231 If the target thread is currently making a foreign call, then the
232 exception will not be raised (and hence 'throwTo' will not return)
233 until the call has completed.  This is the case regardless of whether
234 the call is inside a 'block' or not.
235
236 Important note: the behaviour of 'throwTo' differs from that described in
237 the paper "Asynchronous exceptions in Haskell" 
238 (<http://research.microsoft.com/~simonpj/Papers/asynch-exns.htm>).
239 In the paper, 'throwTo' is non-blocking; but the library implementation adopts
240 a more synchronous design in which 'throwTo' does not return until the exception
241 is received by the target thread.  The trade-off is discussed in Section 8 of the paper.
242 Like any blocking operation, 'throwTo' is therefore interruptible (see Section 4.3 of
243 the paper).
244
245  -}
246 throwTo :: ThreadId -> Exception -> IO ()
247 throwTo (ThreadId id) ex = IO $ \ s ->
248    case (killThread# id ex s) of s1 -> (# s1, () #)
249
250 -- | Returns the 'ThreadId' of the calling thread (GHC only).
251 myThreadId :: IO ThreadId
252 myThreadId = IO $ \s ->
253    case (myThreadId# s) of (# s1, id #) -> (# s1, ThreadId id #)
254
255
256 -- |The 'yield' action allows (forces, in a co-operative multitasking
257 -- implementation) a context-switch to any other currently runnable
258 -- threads (if any), and is occasionally useful when implementing
259 -- concurrency abstractions.
260 yield :: IO ()
261 yield = IO $ \s -> 
262    case (yield# s) of s1 -> (# s1, () #)
263
264 {- | 'labelThread' stores a string as identifier for this thread if
265 you built a RTS with debugging support. This identifier will be used in
266 the debugging output to make distinction of different threads easier
267 (otherwise you only have the thread state object\'s address in the heap).
268
269 Other applications like the graphical Concurrent Haskell Debugger
270 (<http://www.informatik.uni-kiel.de/~fhu/chd/>) may choose to overload
271 'labelThread' for their purposes as well.
272 -}
273
274 labelThread :: ThreadId -> String -> IO ()
275 labelThread (ThreadId t) str = IO $ \ s ->
276    let ps  = packCString# str
277        adr = byteArrayContents# ps in
278      case (labelThread# t adr s) of s1 -> (# s1, () #)
279
280 --      Nota Bene: 'pseq' used to be 'seq'
281 --                 but 'seq' is now defined in PrelGHC
282 --
283 -- "pseq" is defined a bit weirdly (see below)
284 --
285 -- The reason for the strange "lazy" call is that
286 -- it fools the compiler into thinking that pseq  and par are non-strict in
287 -- their second argument (even if it inlines pseq at the call site).
288 -- If it thinks pseq is strict in "y", then it often evaluates
289 -- "y" before "x", which is totally wrong.  
290
291 {-# INLINE pseq  #-}
292 pseq :: a -> b -> b
293 pseq  x y = x `seq` lazy y
294
295 {-# INLINE par  #-}
296 par :: a -> b -> b
297 par  x y = case (par# x) of { _ -> lazy y }
298 \end{code}
299
300
301 %************************************************************************
302 %*                                                                      *
303 \subsection[stm]{Transactional heap operations}
304 %*                                                                      *
305 %************************************************************************
306
307 TVars are shared memory locations which support atomic memory
308 transactions.
309
310 \begin{code}
311 -- |A monad supporting atomic memory transactions.
312 newtype STM a = STM (State# RealWorld -> (# State# RealWorld, a #))
313
314 unSTM :: STM a -> (State# RealWorld -> (# State# RealWorld, a #))
315 unSTM (STM a) = a
316
317 INSTANCE_TYPEABLE1(STM,stmTc,"STM")
318
319 instance  Functor STM where
320    fmap f x = x >>= (return . f)
321
322 instance  Monad STM  where
323     {-# INLINE return #-}
324     {-# INLINE (>>)   #-}
325     {-# INLINE (>>=)  #-}
326     m >> k      = thenSTM m k
327     return x    = returnSTM x
328     m >>= k     = bindSTM m k
329
330 bindSTM :: STM a -> (a -> STM b) -> STM b
331 bindSTM (STM m) k = STM ( \s ->
332   case m s of 
333     (# new_s, a #) -> unSTM (k a) new_s
334   )
335
336 thenSTM :: STM a -> STM b -> STM b
337 thenSTM (STM m) k = STM ( \s ->
338   case m s of 
339     (# new_s, a #) -> unSTM k new_s
340   )
341
342 returnSTM :: a -> STM a
343 returnSTM x = STM (\s -> (# s, x #))
344
345 -- | Unsafely performs IO in the STM monad.
346 unsafeIOToSTM :: IO a -> STM a
347 unsafeIOToSTM (IO m) = STM m
348
349 -- |Perform a series of STM actions atomically.
350 --
351 -- You cannot use 'atomically' inside an 'unsafePerformIO' or 'unsafeInterleaveIO'. 
352 -- Any attempt to do so will result in a runtime error.  (Reason: allowing
353 -- this would effectively allow a transaction inside a transaction, depending
354 -- on exactly when the thunk is evaluated.)
355 --
356 -- However, see 'newTVarIO', which can be called inside 'unsafePerformIO',
357 -- and which allows top-level TVars to be allocated.
358
359 atomically :: STM a -> IO a
360 atomically (STM m) = IO (\s -> (atomically# m) s )
361
362 -- |Retry execution of the current memory transaction because it has seen
363 -- values in TVars which mean that it should not continue (e.g. the TVars
364 -- represent a shared buffer that is now empty).  The implementation may
365 -- block the thread until one of the TVars that it has read from has been
366 -- udpated. (GHC only)
367 retry :: STM a
368 retry = STM $ \s# -> retry# s#
369
370 -- |Compose two alternative STM actions (GHC only).  If the first action
371 -- completes without retrying then it forms the result of the orElse.
372 -- Otherwise, if the first action retries, then the second action is
373 -- tried in its place.  If both actions retry then the orElse as a
374 -- whole retries.
375 orElse :: STM a -> STM a -> STM a
376 orElse (STM m) e = STM $ \s -> catchRetry# m (unSTM e) s
377
378 -- |Exception handling within STM actions.
379 catchSTM :: STM a -> (Exception -> STM a) -> STM a
380 catchSTM (STM m) k = STM $ \s -> catchSTM# m (\ex -> unSTM (k ex)) s
381
382 -- | Low-level primitive on which always and alwaysSucceeds are built.
383 -- checkInv differs form these in that (i) the invariant is not 
384 -- checked when checkInv is called, only at the end of this and
385 -- subsequent transcations, (ii) the invariant failure is indicated
386 -- by raising an exception.
387 checkInv :: STM a -> STM ()
388 checkInv (STM m) = STM (\s -> (check# m) s)
389
390 -- | alwaysSucceeds adds a new invariant that must be true when passed
391 -- to alwaysSucceeds, at the end of the current transaction, and at
392 -- the end of every subsequent transaction.  If it fails at any
393 -- of those points then the transaction violating it is aborted
394 -- and the exception raised by the invariant is propagated.
395 alwaysSucceeds :: STM a -> STM ()
396 alwaysSucceeds i = do ( do i ; retry ) `orElse` ( return () ) 
397                       checkInv i
398
399 -- | always is a variant of alwaysSucceeds in which the invariant is
400 -- expressed as an STM Bool action that must return True.  Returning
401 -- False or raising an exception are both treated as invariant failures.
402 always :: STM Bool -> STM ()
403 always i = alwaysSucceeds ( do v <- i
404                                if (v) then return () else ( error "Transacional invariant violation" ) )
405
406 -- |Shared memory locations that support atomic memory transactions.
407 data TVar a = TVar (TVar# RealWorld a)
408
409 INSTANCE_TYPEABLE1(TVar,tvarTc,"TVar")
410
411 instance Eq (TVar a) where
412         (TVar tvar1#) == (TVar tvar2#) = sameTVar# tvar1# tvar2#
413
414 -- |Create a new TVar holding a value supplied
415 newTVar :: a -> STM (TVar a)
416 newTVar val = STM $ \s1# ->
417     case newTVar# val s1# of
418          (# s2#, tvar# #) -> (# s2#, TVar tvar# #)
419
420 -- |@IO@ version of 'newTVar'.  This is useful for creating top-level
421 -- 'TVar's using 'System.IO.Unsafe.unsafePerformIO', because using
422 -- 'atomically' inside 'System.IO.Unsafe.unsafePerformIO' isn't
423 -- possible.
424 newTVarIO :: a -> IO (TVar a)
425 newTVarIO val = IO $ \s1# ->
426     case newTVar# val s1# of
427          (# s2#, tvar# #) -> (# s2#, TVar tvar# #)
428
429 -- |Return the current value stored in a TVar
430 readTVar :: TVar a -> STM a
431 readTVar (TVar tvar#) = STM $ \s# -> readTVar# tvar# s#
432
433 -- |Write the supplied value into a TVar
434 writeTVar :: TVar a -> a -> STM ()
435 writeTVar (TVar tvar#) val = STM $ \s1# ->
436     case writeTVar# tvar# val s1# of
437          s2# -> (# s2#, () #)
438   
439 \end{code}
440
441 %************************************************************************
442 %*                                                                      *
443 \subsection[mvars]{M-Structures}
444 %*                                                                      *
445 %************************************************************************
446
447 M-Vars are rendezvous points for concurrent threads.  They begin
448 empty, and any attempt to read an empty M-Var blocks.  When an M-Var
449 is written, a single blocked thread may be freed.  Reading an M-Var
450 toggles its state from full back to empty.  Therefore, any value
451 written to an M-Var may only be read once.  Multiple reads and writes
452 are allowed, but there must be at least one read between any two
453 writes.
454
455 \begin{code}
456 --Defined in IOBase to avoid cycle: data MVar a = MVar (SynchVar# RealWorld a)
457
458 -- |Create an 'MVar' which is initially empty.
459 newEmptyMVar  :: IO (MVar a)
460 newEmptyMVar = IO $ \ s# ->
461     case newMVar# s# of
462          (# s2#, svar# #) -> (# s2#, MVar svar# #)
463
464 -- |Create an 'MVar' which contains the supplied value.
465 newMVar :: a -> IO (MVar a)
466 newMVar value =
467     newEmptyMVar        >>= \ mvar ->
468     putMVar mvar value  >>
469     return mvar
470
471 -- |Return the contents of the 'MVar'.  If the 'MVar' is currently
472 -- empty, 'takeMVar' will wait until it is full.  After a 'takeMVar', 
473 -- the 'MVar' is left empty.
474 -- 
475 -- There are two further important properties of 'takeMVar':
476 --
477 --   * 'takeMVar' is single-wakeup.  That is, if there are multiple
478 --     threads blocked in 'takeMVar', and the 'MVar' becomes full,
479 --     only one thread will be woken up.  The runtime guarantees that
480 --     the woken thread completes its 'takeMVar' operation.
481 --
482 --   * When multiple threads are blocked on an 'MVar', they are
483 --     woken up in FIFO order.  This is useful for providing
484 --     fairness properties of abstractions built using 'MVar's.
485 --
486 takeMVar :: MVar a -> IO a
487 takeMVar (MVar mvar#) = IO $ \ s# -> takeMVar# mvar# s#
488
489 -- |Put a value into an 'MVar'.  If the 'MVar' is currently full,
490 -- 'putMVar' will wait until it becomes empty.
491 --
492 -- There are two further important properties of 'putMVar':
493 --
494 --   * 'putMVar' is single-wakeup.  That is, if there are multiple
495 --     threads blocked in 'putMVar', and the 'MVar' becomes empty,
496 --     only one thread will be woken up.  The runtime guarantees that
497 --     the woken thread completes its 'putMVar' operation.
498 --
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.
502 --
503 putMVar  :: MVar a -> a -> IO ()
504 putMVar (MVar mvar#) x = IO $ \ s# ->
505     case putMVar# mvar# x s# of
506         s2# -> (# s2#, () #)
507
508 -- |A non-blocking version of 'takeMVar'.  The 'tryTakeMVar' function
509 -- returns immediately, with 'Nothing' if the 'MVar' was empty, or
510 -- @'Just' a@ if the 'MVar' was full with contents @a@.  After 'tryTakeMVar',
511 -- the 'MVar' is left empty.
512 tryTakeMVar :: MVar a -> IO (Maybe a)
513 tryTakeMVar (MVar m) = IO $ \ s ->
514     case tryTakeMVar# m s of
515         (# s, 0#, _ #) -> (# s, Nothing #)      -- MVar is empty
516         (# s, _,  a #) -> (# s, Just a  #)      -- MVar is full
517
518 -- |A non-blocking version of 'putMVar'.  The 'tryPutMVar' function
519 -- attempts to put the value @a@ into the 'MVar', returning 'True' if
520 -- it was successful, or 'False' otherwise.
521 tryPutMVar  :: MVar a -> a -> IO Bool
522 tryPutMVar (MVar mvar#) x = IO $ \ s# ->
523     case tryPutMVar# mvar# x s# of
524         (# s, 0# #) -> (# s, False #)
525         (# s, _  #) -> (# s, True #)
526
527 -- |Check whether a given 'MVar' is empty.
528 --
529 -- Notice that the boolean value returned  is just a snapshot of
530 -- the state of the MVar. By the time you get to react on its result,
531 -- the MVar may have been filled (or emptied) - so be extremely
532 -- careful when using this operation.   Use 'tryTakeMVar' instead if possible.
533 isEmptyMVar :: MVar a -> IO Bool
534 isEmptyMVar (MVar mv#) = IO $ \ s# -> 
535     case isEmptyMVar# mv# s# of
536         (# s2#, flg #) -> (# s2#, not (flg ==# 0#) #)
537
538 -- |Add a finalizer to an 'MVar' (GHC only).  See "Foreign.ForeignPtr" and
539 -- "System.Mem.Weak" for more about finalizers.
540 addMVarFinalizer :: MVar a -> IO () -> IO ()
541 addMVarFinalizer (MVar m) finalizer = 
542   IO $ \s -> case mkWeak# m () finalizer s of { (# s1, w #) -> (# s1, () #) }
543 \end{code}
544
545
546 %************************************************************************
547 %*                                                                      *
548 \subsection{Thread waiting}
549 %*                                                                      *
550 %************************************************************************
551
552 \begin{code}
553 #ifdef mingw32_HOST_OS
554
555 -- Note: threadDelay, threadWaitRead and threadWaitWrite aren't really functional
556 -- on Win32, but left in there because lib code (still) uses them (the manner
557 -- in which they're used doesn't cause problems on a Win32 platform though.)
558
559 asyncRead :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
560 asyncRead  (I# fd) (I# isSock) (I# len) (Ptr buf) =
561   IO $ \s -> case asyncRead# fd isSock len buf s of 
562                (# s, len#, err# #) -> (# s, (I# len#, I# err#) #)
563
564 asyncWrite :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
565 asyncWrite  (I# fd) (I# isSock) (I# len) (Ptr buf) =
566   IO $ \s -> case asyncWrite# fd isSock len buf s of 
567                (# s, len#, err# #) -> (# s, (I# len#, I# err#) #)
568
569 asyncDoProc :: FunPtr (Ptr a -> IO Int) -> Ptr a -> IO Int
570 asyncDoProc (FunPtr proc) (Ptr param) = 
571     -- the 'length' value is ignored; simplifies implementation of
572     -- the async*# primops to have them all return the same result.
573   IO $ \s -> case asyncDoProc# proc param s  of 
574                (# s, len#, err# #) -> (# s, I# err# #)
575
576 -- to aid the use of these primops by the IO Handle implementation,
577 -- provide the following convenience funs:
578
579 -- this better be a pinned byte array!
580 asyncReadBA :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int,Int)
581 asyncReadBA fd isSock len off bufB = 
582   asyncRead fd isSock len ((Ptr (byteArrayContents# (unsafeCoerce# bufB))) `plusPtr` off)
583   
584 asyncWriteBA :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int,Int)
585 asyncWriteBA fd isSock len off bufB = 
586   asyncWrite fd isSock len ((Ptr (byteArrayContents# (unsafeCoerce# bufB))) `plusPtr` off)
587
588 #endif
589
590 -- -----------------------------------------------------------------------------
591 -- Thread IO API
592
593 -- | Block the current thread until data is available to read on the
594 -- given file descriptor (GHC only).
595 threadWaitRead :: Fd -> IO ()
596 threadWaitRead fd
597 #ifndef mingw32_HOST_OS
598   | threaded  = waitForReadEvent fd
599 #endif
600   | otherwise = IO $ \s -> 
601         case fromIntegral fd of { I# fd# ->
602         case waitRead# fd# s of { s -> (# s, () #)
603         }}
604
605 -- | Block the current thread until data can be written to the
606 -- given file descriptor (GHC only).
607 threadWaitWrite :: Fd -> IO ()
608 threadWaitWrite fd
609 #ifndef mingw32_HOST_OS
610   | threaded  = waitForWriteEvent fd
611 #endif
612   | otherwise = IO $ \s -> 
613         case fromIntegral fd of { I# fd# ->
614         case waitWrite# fd# s of { s -> (# s, () #)
615         }}
616
617 -- | Suspends the current thread for a given number of microseconds
618 -- (GHC only).
619 --
620 -- Note that the resolution used by the Haskell runtime system's
621 -- internal timer is 1\/50 second, and 'threadDelay' will round its
622 -- argument up to the nearest multiple of this resolution.
623 --
624 -- There is no guarantee that the thread will be rescheduled promptly
625 -- when the delay has expired, but the thread will never continue to
626 -- run /earlier/ than specified.
627 --
628 threadDelay :: Int -> IO ()
629 threadDelay time
630   | threaded  = waitForDelayEvent time
631   | otherwise = IO $ \s -> 
632         case fromIntegral time of { I# time# ->
633         case delay# time# s of { s -> (# s, () #)
634         }}
635
636 registerDelay :: Int -> IO (TVar Bool)
637 registerDelay usecs 
638   | threaded = waitForDelayEventSTM usecs
639   | otherwise = error "registerDelay: requires -threaded"
640
641 foreign import ccall unsafe "rtsSupportsBoundThreads" threaded :: Bool
642
643 waitForDelayEvent :: Int -> IO ()
644 waitForDelayEvent usecs = do
645   m <- newEmptyMVar
646   now <- getTicksOfDay
647   let target = now + usecs `quot` tick_usecs
648   atomicModifyIORef pendingDelays (\xs -> (Delay target m : xs, ()))
649   prodServiceThread
650   takeMVar m
651
652 -- Delays for use in STM
653 waitForDelayEventSTM :: Int -> IO (TVar Bool)
654 waitForDelayEventSTM usecs = do
655    t <- atomically $ newTVar False
656    now <- getTicksOfDay
657    let target = now + usecs `quot` tick_usecs
658    atomicModifyIORef pendingDelays (\xs -> (DelaySTM target t : xs, ()))
659    prodServiceThread
660    return t  
661     
662 calculateTarget :: Int -> IO Int
663 calculateTarget usecs = do
664     now <- getTicksOfDay
665     let -- Convert usecs to ticks, rounding up as we must wait /at least/
666         -- as long as we are told
667         usecs' = (usecs + tick_usecs - 1) `quot` tick_usecs
668         target = now + 1 -- getTicksOfDay will have rounded down, but
669                          -- again we need to wait for /at least/ as long
670                          -- as we are told, so add 1 to it
671                + usecs'
672     return target
673
674 -- ----------------------------------------------------------------------------
675 -- Threaded RTS implementation of threadWaitRead, threadWaitWrite, threadDelay
676
677 -- In the threaded RTS, we employ a single IO Manager thread to wait
678 -- for all outstanding IO requests (threadWaitRead,threadWaitWrite)
679 -- and delays (threadDelay).  
680 --
681 -- We can do this because in the threaded RTS the IO Manager can make
682 -- a non-blocking call to select(), so we don't have to do select() in
683 -- the scheduler as we have to in the non-threaded RTS.  We get performance
684 -- benefits from doing it this way, because we only have to restart the select()
685 -- when a new request arrives, rather than doing one select() each time
686 -- around the scheduler loop.  Furthermore, the scheduler can be simplified
687 -- by not having to check for completed IO requests.
688
689 -- Issues, possible problems:
690 --
691 --      - we might want bound threads to just do the blocking
692 --        operation rather than communicating with the IO manager
693 --        thread.  This would prevent simgle-threaded programs which do
694 --        IO from requiring multiple OS threads.  However, it would also
695 --        prevent bound threads waiting on IO from being killed or sent
696 --        exceptions.
697 --
698 --      - Apprently exec() doesn't work on Linux in a multithreaded program.
699 --        I couldn't repeat this.
700 --
701 --      - How do we handle signal delivery in the multithreaded RTS?
702 --
703 --      - forkProcess will kill the IO manager thread.  Let's just
704 --        hope we don't need to do any blocking IO between fork & exec.
705
706 #ifndef mingw32_HOST_OS
707 data IOReq
708   = Read   {-# UNPACK #-} !Fd {-# UNPACK #-} !(MVar ())
709   | Write  {-# UNPACK #-} !Fd {-# UNPACK #-} !(MVar ())
710 #endif
711
712 data DelayReq
713   = Delay    {-# UNPACK #-} !Int {-# UNPACK #-} !(MVar ())
714   | DelaySTM {-# UNPACK #-} !Int {-# UNPACK #-} !(TVar Bool)
715
716 #ifndef mingw32_HOST_OS
717 pendingEvents :: IORef [IOReq]
718 #endif
719 pendingDelays :: IORef [DelayReq]
720         -- could use a strict list or array here
721 {-# NOINLINE pendingEvents #-}
722 {-# NOINLINE pendingDelays #-}
723 (pendingEvents,pendingDelays) = unsafePerformIO $ do
724   startIOManagerThread
725   reqs <- newIORef []
726   dels <- newIORef []
727   return (reqs, dels)
728         -- the first time we schedule an IO request, the service thread
729         -- will be created (cool, huh?)
730
731 ensureIOManagerIsRunning :: IO ()
732 ensureIOManagerIsRunning 
733   | threaded  = seq pendingEvents $ return ()
734   | otherwise = return ()
735
736 insertDelay :: DelayReq -> [DelayReq] -> [DelayReq]
737 insertDelay d [] = [d]
738 insertDelay d1 ds@(d2 : rest)
739   | delayTime d1 <= delayTime d2 = d1 : ds
740   | otherwise                    = d2 : insertDelay d1 rest
741
742 delayTime (Delay t _) = t
743 delayTime (DelaySTM t _) = t
744
745 type Ticks = Int
746 tick_freq  = 50 :: Ticks  -- accuracy of threadDelay (ticks per sec)
747 tick_usecs = 1000000 `quot` tick_freq :: Int
748 tick_msecs = 1000 `quot` tick_freq :: Int
749
750 -- XXX: move into GHC.IOBase from Data.IORef?
751 atomicModifyIORef :: IORef a -> (a -> (a,b)) -> IO b
752 atomicModifyIORef (IORef (STRef r#)) f = IO $ \s -> atomicModifyMutVar# r# f s
753
754 foreign import ccall unsafe "getTicksOfDay" 
755   getTicksOfDay :: IO Ticks
756
757 #ifdef mingw32_HOST_OS
758 -- ----------------------------------------------------------------------------
759 -- Windows IO manager thread
760
761 startIOManagerThread :: IO ()
762 startIOManagerThread = do
763   wakeup <- c_getIOManagerEvent
764   forkIO $ service_loop wakeup []
765   return ()
766
767 service_loop :: HANDLE          -- read end of pipe
768              -> [DelayReq]      -- current delay requests
769              -> IO ()
770
771 service_loop wakeup old_delays = do
772   -- pick up new delay requests
773   new_delays <- atomicModifyIORef pendingDelays (\a -> ([],a))
774   let  delays = foldr insertDelay old_delays new_delays
775
776   now <- getTicksOfDay
777   (delays', timeout) <- getDelay now delays
778
779   r <- c_WaitForSingleObject wakeup timeout
780   case r of
781     0xffffffff -> do c_maperrno; throwErrno "service_loop"
782     0 -> do
783         r <- c_readIOManagerEvent
784         exit <- 
785               case r of
786                 _ | r == io_MANAGER_WAKEUP -> return False
787                 _ | r == io_MANAGER_DIE    -> return True
788                 0 -> return False -- spurious wakeup
789                 r -> do start_console_handler (r `shiftR` 1); return False
790         if exit
791           then return ()
792           else service_cont wakeup delays'
793
794     _other -> service_cont wakeup delays' -- probably timeout        
795
796 service_cont wakeup delays = do
797   takeMVar prodding
798   putMVar prodding False
799   service_loop wakeup delays
800
801 -- must agree with rts/win32/ThrIOManager.c
802 io_MANAGER_WAKEUP = 0xffffffff :: Word32
803 io_MANAGER_DIE    = 0xfffffffe :: Word32
804
805 start_console_handler :: Word32 -> IO ()
806 start_console_handler r = do                   
807   stableptr <- peek console_handler
808   forkIO $ do io <- deRefStablePtr stableptr; io (fromIntegral r)
809   return ()
810
811 foreign import ccall "&console_handler" 
812    console_handler :: Ptr (StablePtr (CInt -> IO ()))
813
814 stick :: IORef HANDLE
815 {-# NOINLINE stick #-}
816 stick = unsafePerformIO (newIORef nullPtr)
817
818 prodding :: MVar Bool
819 {-# NOINLINE prodding #-}
820 prodding = unsafePerformIO (newMVar False)
821
822 prodServiceThread :: IO ()
823 prodServiceThread = do
824   b <- takeMVar prodding
825   if (not b) 
826     then do hdl <- readIORef stick
827             c_sendIOManagerEvent io_MANAGER_WAKEUP
828     else return ()
829   putMVar prodding True
830
831 -- Walk the queue of pending delays, waking up any that have passed
832 -- and return the smallest delay to wait for.  The queue of pending
833 -- delays is kept ordered.
834 getDelay :: Ticks -> [DelayReq] -> IO ([DelayReq], DWORD)
835 getDelay now [] = return ([], iNFINITE)
836 getDelay now all@(d : rest) 
837   = case d of
838      Delay time m | now >= time -> do
839         putMVar m ()
840         getDelay now rest
841      DelaySTM time t | now >= time -> do
842         atomically $ writeTVar t True
843         getDelay now rest
844      _otherwise ->
845         return (all, (fromIntegral (delayTime d - now) * 
846                         fromIntegral tick_msecs))
847                         -- delay is in millisecs for WaitForSingleObject
848
849 -- ToDo: this just duplicates part of System.Win32.Types, which isn't
850 -- available yet.  We should move some Win32 functionality down here,
851 -- maybe as part of the grand reorganisation of the base package...
852 type HANDLE       = Ptr ()
853 type DWORD        = Word32
854
855 iNFINITE = 0xFFFFFFFF :: DWORD -- urgh
856
857 foreign import ccall unsafe "getIOManagerEvent" -- in the RTS (ThrIOManager.c)
858   c_getIOManagerEvent :: IO HANDLE
859
860 foreign import ccall unsafe "readIOManagerEvent" -- in the RTS (ThrIOManager.c)
861   c_readIOManagerEvent :: IO Word32
862
863 foreign import ccall unsafe "sendIOManagerEvent" -- in the RTS (ThrIOManager.c)
864   c_sendIOManagerEvent :: Word32 -> IO ()
865
866 foreign import ccall unsafe "maperrno"             -- in runProcess.c
867    c_maperrno :: IO ()
868
869 foreign import stdcall "WaitForSingleObject"
870    c_WaitForSingleObject :: HANDLE -> DWORD -> IO DWORD
871
872 #else
873 -- ----------------------------------------------------------------------------
874 -- Unix IO manager thread, using select()
875
876 startIOManagerThread :: IO ()
877 startIOManagerThread = do
878         allocaArray 2 $ \fds -> do
879         throwErrnoIfMinus1 "startIOManagerThread" (c_pipe fds)
880         rd_end <- peekElemOff fds 0
881         wr_end <- peekElemOff fds 1
882         writeIORef stick (fromIntegral wr_end)
883         c_setIOManagerPipe wr_end
884         forkIO $ do
885             allocaBytes sizeofFdSet   $ \readfds -> do
886             allocaBytes sizeofFdSet   $ \writefds -> do 
887             allocaBytes sizeofTimeVal $ \timeval -> do
888             service_loop (fromIntegral rd_end) readfds writefds timeval [] []
889         return ()
890
891 service_loop
892    :: Fd                -- listen to this for wakeup calls
893    -> Ptr CFdSet
894    -> Ptr CFdSet
895    -> Ptr CTimeVal
896    -> [IOReq]
897    -> [DelayReq]
898    -> IO ()
899 service_loop wakeup readfds writefds ptimeval old_reqs old_delays = do
900
901   -- pick up new IO requests
902   new_reqs <- atomicModifyIORef pendingEvents (\a -> ([],a))
903   let reqs = new_reqs ++ old_reqs
904
905   -- pick up new delay requests
906   new_delays <- atomicModifyIORef pendingDelays (\a -> ([],a))
907   let  delays = foldr insertDelay old_delays new_delays
908
909   -- build the FDSets for select()
910   fdZero readfds
911   fdZero writefds
912   fdSet wakeup readfds
913   maxfd <- buildFdSets 0 readfds writefds reqs
914
915   -- perform the select()
916   let do_select delays = do
917           -- check the current time and wake up any thread in
918           -- threadDelay whose timeout has expired.  Also find the
919           -- timeout value for the select() call.
920           now <- getTicksOfDay
921           (delays', timeout) <- getDelay now ptimeval delays
922
923           res <- c_select ((max wakeup maxfd)+1) readfds writefds 
924                         nullPtr timeout
925           if (res == -1)
926              then do
927                 err <- getErrno
928                 case err of
929                   _ | err == eINTR ->  do_select delays'
930                         -- EINTR: just redo the select()
931                   _ | err == eBADF ->  return (True, delays)
932                         -- EBADF: one of the file descriptors is closed or bad,
933                         -- we don't know which one, so wake everyone up.
934                   _ | otherwise    ->  throwErrno "select"
935                         -- otherwise (ENOMEM or EINVAL) something has gone
936                         -- wrong; report the error.
937              else
938                 return (False,delays')
939
940   (wakeup_all,delays') <- do_select delays
941
942   exit <-
943     if wakeup_all then return False
944       else do
945         b <- fdIsSet wakeup readfds
946         if b == 0 
947           then return False
948           else alloca $ \p -> do 
949                  c_read (fromIntegral wakeup) p 1; return ()
950                  s <- peek p            
951                  case s of
952                   _ | s == io_MANAGER_WAKEUP -> return False
953                   _ | s == io_MANAGER_DIE    -> return True
954                   _ -> do handler_tbl <- peek handlers
955                           sp <- peekElemOff handler_tbl (fromIntegral s)
956                           forkIO (do io <- deRefStablePtr sp; io)
957                           return False
958
959   if exit then return () else do
960
961   takeMVar prodding
962   putMVar prodding False
963
964   reqs' <- if wakeup_all then do wakeupAll reqs; return []
965                          else completeRequests reqs readfds writefds []
966
967   service_loop wakeup readfds writefds ptimeval reqs' delays'
968
969 io_MANAGER_WAKEUP = 0xff :: CChar
970 io_MANAGER_DIE    = 0xfe :: CChar
971
972 stick :: IORef Fd
973 {-# NOINLINE stick #-}
974 stick = unsafePerformIO (newIORef 0)
975
976 prodding :: MVar Bool
977 {-# NOINLINE prodding #-}
978 prodding = unsafePerformIO (newMVar False)
979
980 prodServiceThread :: IO ()
981 prodServiceThread = do
982   b <- takeMVar prodding
983   if (not b) 
984     then do fd <- readIORef stick
985             with io_MANAGER_WAKEUP $ \pbuf -> do 
986                 c_write (fromIntegral fd) pbuf 1; return ()
987     else return ()
988   putMVar prodding True
989
990 foreign import ccall "&signal_handlers" handlers :: Ptr (Ptr (StablePtr (IO ())))
991
992 foreign import ccall "setIOManagerPipe"
993   c_setIOManagerPipe :: CInt -> IO ()
994
995 -- -----------------------------------------------------------------------------
996 -- IO requests
997
998 buildFdSets maxfd readfds writefds [] = return maxfd
999 buildFdSets maxfd readfds writefds (Read fd m : reqs)
1000   | fd >= fD_SETSIZE =  error "buildFdSets: file descriptor out of range"
1001   | otherwise        =  do
1002         fdSet fd readfds
1003         buildFdSets (max maxfd fd) readfds writefds reqs
1004 buildFdSets maxfd readfds writefds (Write fd m : reqs)
1005   | fd >= fD_SETSIZE =  error "buildFdSets: file descriptor out of range"
1006   | otherwise        =  do
1007         fdSet fd writefds
1008         buildFdSets (max maxfd fd) readfds writefds reqs
1009
1010 completeRequests [] _ _ reqs' = return reqs'
1011 completeRequests (Read fd m : reqs) readfds writefds reqs' = do
1012   b <- fdIsSet fd readfds
1013   if b /= 0
1014     then do putMVar m (); completeRequests reqs readfds writefds reqs'
1015     else completeRequests reqs readfds writefds (Read fd m : reqs')
1016 completeRequests (Write fd m : reqs) readfds writefds reqs' = do
1017   b <- fdIsSet fd writefds
1018   if b /= 0
1019     then do putMVar m (); completeRequests reqs readfds writefds reqs'
1020     else completeRequests reqs readfds writefds (Write fd m : reqs')
1021
1022 wakeupAll [] = return ()
1023 wakeupAll (Read  fd m : reqs) = do putMVar m (); wakeupAll reqs
1024 wakeupAll (Write fd m : reqs) = do putMVar m (); wakeupAll reqs
1025
1026 waitForReadEvent :: Fd -> IO ()
1027 waitForReadEvent fd = do
1028   m <- newEmptyMVar
1029   atomicModifyIORef pendingEvents (\xs -> (Read fd m : xs, ()))
1030   prodServiceThread
1031   takeMVar m
1032
1033 waitForWriteEvent :: Fd -> IO ()
1034 waitForWriteEvent fd = do
1035   m <- newEmptyMVar
1036   atomicModifyIORef pendingEvents (\xs -> (Write fd m : xs, ()))
1037   prodServiceThread
1038   takeMVar m
1039
1040 -- -----------------------------------------------------------------------------
1041 -- Delays
1042
1043 -- Walk the queue of pending delays, waking up any that have passed
1044 -- and return the smallest delay to wait for.  The queue of pending
1045 -- delays is kept ordered.
1046 getDelay :: Ticks -> Ptr CTimeVal -> [DelayReq] -> IO ([DelayReq], Ptr CTimeVal)
1047 getDelay now ptimeval [] = return ([],nullPtr)
1048 getDelay now ptimeval all@(d : rest) 
1049   = case d of
1050      Delay time m | now >= time -> do
1051         putMVar m ()
1052         getDelay now ptimeval rest
1053      DelaySTM time t | now >= time -> do
1054         atomically $ writeTVar t True
1055         getDelay now ptimeval rest
1056      _otherwise -> do
1057         setTimevalTicks ptimeval (delayTime d - now)
1058         return (all,ptimeval)
1059
1060 newtype CTimeVal = CTimeVal ()
1061
1062 foreign import ccall unsafe "sizeofTimeVal"
1063   sizeofTimeVal :: Int
1064
1065 foreign import ccall unsafe "setTimevalTicks" 
1066   setTimevalTicks :: Ptr CTimeVal -> Ticks -> IO ()
1067
1068 {- 
1069   On Win32 we're going to have a single Pipe, and a
1070   waitForSingleObject with the delay time.  For signals, we send a
1071   byte down the pipe just like on Unix.
1072 -}
1073
1074 -- ----------------------------------------------------------------------------
1075 -- select() interface
1076
1077 -- ToDo: move to System.Posix.Internals?
1078
1079 newtype CFdSet = CFdSet ()
1080
1081 foreign import ccall safe "select"
1082   c_select :: Fd -> Ptr CFdSet -> Ptr CFdSet -> Ptr CFdSet -> Ptr CTimeVal
1083            -> IO CInt
1084
1085 foreign import ccall unsafe "hsFD_SETSIZE"
1086   fD_SETSIZE :: Fd
1087
1088 foreign import ccall unsafe "hsFD_CLR"
1089   fdClr :: Fd -> Ptr CFdSet -> IO ()
1090
1091 foreign import ccall unsafe "hsFD_ISSET"
1092   fdIsSet :: Fd -> Ptr CFdSet -> IO CInt
1093
1094 foreign import ccall unsafe "hsFD_SET"
1095   fdSet :: Fd -> Ptr CFdSet -> IO ()
1096
1097 foreign import ccall unsafe "hsFD_ZERO"
1098   fdZero :: Ptr CFdSet -> IO ()
1099
1100 foreign import ccall unsafe "sizeof_fd_set"
1101   sizeofFdSet :: Int
1102
1103 #endif
1104
1105 \end{code}