add forkIOWithUnmask, forkOnIOWithUnmask; deprecate forkIOUnmasked
[ghc-base.git] / Control / Concurrent.hs
1 {-# LANGUAGE CPP
2            , ForeignFunctionInterface
3            , MagicHash
4            , UnboxedTuples
5            , ScopedTypeVariables
6   #-}
7 {-# OPTIONS_GHC -fno-warn-unused-imports #-}
8
9 -----------------------------------------------------------------------------
10 -- |
11 -- Module      :  Control.Concurrent
12 -- Copyright   :  (c) The University of Glasgow 2001
13 -- License     :  BSD-style (see the file libraries/base/LICENSE)
14 -- 
15 -- Maintainer  :  libraries@haskell.org
16 -- Stability   :  experimental
17 -- Portability :  non-portable (concurrency)
18 --
19 -- A common interface to a collection of useful concurrency
20 -- abstractions.
21 --
22 -----------------------------------------------------------------------------
23
24 module Control.Concurrent (
25         -- * Concurrent Haskell
26
27         -- $conc_intro
28
29         -- * Basic concurrency operations
30
31         ThreadId,
32 #ifdef __GLASGOW_HASKELL__
33         myThreadId,
34 #endif
35
36         forkIO,
37 #ifdef __GLASGOW_HASKELL__
38         forkIOWithUnmask,
39         killThread,
40         throwTo,
41 #endif
42
43         -- * Scheduling
44
45         -- $conc_scheduling     
46         yield,                  -- :: IO ()
47
48         -- ** Blocking
49
50         -- $blocking
51
52 #ifdef __GLASGOW_HASKELL__
53         -- ** Waiting
54         threadDelay,            -- :: Int -> IO ()
55         threadWaitRead,         -- :: Int -> IO ()
56         threadWaitWrite,        -- :: Int -> IO ()
57 #endif
58
59         -- * Communication abstractions
60
61         module Control.Concurrent.MVar,
62         module Control.Concurrent.Chan,
63         module Control.Concurrent.QSem,
64         module Control.Concurrent.QSemN,
65         module Control.Concurrent.SampleVar,
66
67         -- * Merging of streams
68 #ifndef __HUGS__
69         mergeIO,                -- :: [a]   -> [a] -> IO [a]
70         nmergeIO,               -- :: [[a]] -> IO [a]
71 #endif
72         -- $merge
73
74 #ifdef __GLASGOW_HASKELL__
75         -- * Bound Threads
76         -- $boundthreads
77         rtsSupportsBoundThreads,
78         forkOS,
79         isCurrentThreadBound,
80         runInBoundThread,
81         runInUnboundThread,
82 #endif
83
84         -- * GHC's implementation of concurrency
85
86         -- |This section describes features specific to GHC's
87         -- implementation of Concurrent Haskell.
88
89         -- ** Haskell threads and Operating System threads
90
91         -- $osthreads
92
93         -- ** Terminating the program
94
95         -- $termination
96
97         -- ** Pre-emption
98
99         -- $preemption
100
101         -- * Deprecated functions
102         forkIOUnmasked
103
104     ) where
105
106 import Prelude
107
108 import Control.Exception.Base as Exception
109
110 #ifdef __GLASGOW_HASKELL__
111 import GHC.Exception
112 import GHC.Conc hiding (threadWaitRead, threadWaitWrite)
113 import qualified GHC.Conc
114 import GHC.IO           ( IO(..), unsafeInterleaveIO, unsafeUnmask )
115 import GHC.IORef        ( newIORef, readIORef, writeIORef )
116 import GHC.Base
117
118 import System.Posix.Types ( Fd )
119 import Foreign.StablePtr
120 import Foreign.C.Types  ( CInt )
121 import Control.Monad    ( when )
122
123 #ifdef mingw32_HOST_OS
124 import Foreign.C
125 import System.IO
126 #endif
127 #endif
128
129 #ifdef __HUGS__
130 import Hugs.ConcBase
131 #endif
132
133 import Control.Concurrent.MVar
134 import Control.Concurrent.Chan
135 import Control.Concurrent.QSem
136 import Control.Concurrent.QSemN
137 import Control.Concurrent.SampleVar
138
139 #ifdef __HUGS__
140 type ThreadId = ()
141 #endif
142
143 {- $conc_intro
144
145 The concurrency extension for Haskell is described in the paper
146 /Concurrent Haskell/
147 <http://www.haskell.org/ghc/docs/papers/concurrent-haskell.ps.gz>.
148
149 Concurrency is \"lightweight\", which means that both thread creation
150 and context switching overheads are extremely low.  Scheduling of
151 Haskell threads is done internally in the Haskell runtime system, and
152 doesn't make use of any operating system-supplied thread packages.
153
154 However, if you want to interact with a foreign library that expects your
155 program to use the operating system-supplied thread package, you can do so
156 by using 'forkOS' instead of 'forkIO'.
157
158 Haskell threads can communicate via 'MVar's, a kind of synchronised
159 mutable variable (see "Control.Concurrent.MVar").  Several common
160 concurrency abstractions can be built from 'MVar's, and these are
161 provided by the "Control.Concurrent" library.
162 In GHC, threads may also communicate via exceptions.
163 -}
164
165 {- $conc_scheduling
166
167     Scheduling may be either pre-emptive or co-operative,
168     depending on the implementation of Concurrent Haskell (see below
169     for information related to specific compilers).  In a co-operative
170     system, context switches only occur when you use one of the
171     primitives defined in this module.  This means that programs such
172     as:
173
174
175 >   main = forkIO (write 'a') >> write 'b'
176 >     where write c = putChar c >> write c
177
178     will print either @aaaaaaaaaaaaaa...@ or @bbbbbbbbbbbb...@,
179     instead of some random interleaving of @a@s and @b@s.  In
180     practice, cooperative multitasking is sufficient for writing
181     simple graphical user interfaces.  
182 -}
183
184 {- $blocking
185 Different Haskell implementations have different characteristics with
186 regard to which operations block /all/ threads.
187
188 Using GHC without the @-threaded@ option, all foreign calls will block
189 all other Haskell threads in the system, although I\/O operations will
190 not.  With the @-threaded@ option, only foreign calls with the @unsafe@
191 attribute will block all other threads.
192
193 Using Hugs, all I\/O operations and foreign calls will block all other
194 Haskell threads.
195 -}
196
197 #ifndef __HUGS__
198 max_buff_size :: Int
199 max_buff_size = 1
200
201 mergeIO :: [a] -> [a] -> IO [a]
202 nmergeIO :: [[a]] -> IO [a]
203
204 -- $merge
205 -- The 'mergeIO' and 'nmergeIO' functions fork one thread for each
206 -- input list that concurrently evaluates that list; the results are
207 -- merged into a single output list.  
208 --
209 -- Note: Hugs does not provide these functions, since they require
210 -- preemptive multitasking.
211
212 mergeIO ls rs
213  = newEmptyMVar                >>= \ tail_node ->
214    newMVar tail_node           >>= \ tail_list ->
215    newQSem max_buff_size       >>= \ e ->
216    newMVar 2                   >>= \ branches_running ->
217    let
218     buff = (tail_list,e)
219    in
220     forkIO (suckIO branches_running buff ls) >>
221     forkIO (suckIO branches_running buff rs) >>
222     takeMVar tail_node  >>= \ val ->
223     signalQSem e        >>
224     return val
225
226 type Buffer a
227  = (MVar (MVar [a]), QSem)
228
229 suckIO :: MVar Int -> Buffer a -> [a] -> IO ()
230
231 suckIO branches_running buff@(tail_list,e) vs
232  = case vs of
233         [] -> takeMVar branches_running >>= \ val ->
234               if val == 1 then
235                  takeMVar tail_list     >>= \ node ->
236                  putMVar node []        >>
237                  putMVar tail_list node
238               else
239                  putMVar branches_running (val-1)
240         (x:xs) ->
241                 waitQSem e                       >>
242                 takeMVar tail_list               >>= \ node ->
243                 newEmptyMVar                     >>= \ next_node ->
244                 unsafeInterleaveIO (
245                         takeMVar next_node  >>= \ y ->
246                         signalQSem e        >>
247                         return y)                >>= \ next_node_val ->
248                 putMVar node (x:next_node_val)   >>
249                 putMVar tail_list next_node      >>
250                 suckIO branches_running buff xs
251
252 nmergeIO lss
253  = let
254     len = length lss
255    in
256     newEmptyMVar          >>= \ tail_node ->
257     newMVar tail_node     >>= \ tail_list ->
258     newQSem max_buff_size >>= \ e ->
259     newMVar len           >>= \ branches_running ->
260     let
261      buff = (tail_list,e)
262     in
263     mapIO (\ x -> forkIO (suckIO branches_running buff x)) lss >>
264     takeMVar tail_node  >>= \ val ->
265     signalQSem e        >>
266     return val
267   where
268     mapIO f xs = sequence (map f xs)
269 #endif /* __HUGS__ */
270
271 #ifdef __GLASGOW_HASKELL__
272 -- ---------------------------------------------------------------------------
273 -- Bound Threads
274
275 {- $boundthreads
276    #boundthreads#
277
278 Support for multiple operating system threads and bound threads as described
279 below is currently only available in the GHC runtime system if you use the
280 /-threaded/ option when linking.
281
282 Other Haskell systems do not currently support multiple operating system threads.
283
284 A bound thread is a haskell thread that is /bound/ to an operating system
285 thread. While the bound thread is still scheduled by the Haskell run-time
286 system, the operating system thread takes care of all the foreign calls made
287 by the bound thread.
288
289 To a foreign library, the bound thread will look exactly like an ordinary
290 operating system thread created using OS functions like @pthread_create@
291 or @CreateThread@.
292
293 Bound threads can be created using the 'forkOS' function below. All foreign
294 exported functions are run in a bound thread (bound to the OS thread that
295 called the function). Also, the @main@ action of every Haskell program is
296 run in a bound thread.
297
298 Why do we need this? Because if a foreign library is called from a thread
299 created using 'forkIO', it won't have access to any /thread-local state/ - 
300 state variables that have specific values for each OS thread
301 (see POSIX's @pthread_key_create@ or Win32's @TlsAlloc@). Therefore, some
302 libraries (OpenGL, for example) will not work from a thread created using
303 'forkIO'. They work fine in threads created using 'forkOS' or when called
304 from @main@ or from a @foreign export@.
305
306 In terms of performance, 'forkOS' (aka bound) threads are much more
307 expensive than 'forkIO' (aka unbound) threads, because a 'forkOS'
308 thread is tied to a particular OS thread, whereas a 'forkIO' thread
309 can be run by any OS thread.  Context-switching between a 'forkOS'
310 thread and a 'forkIO' thread is many times more expensive than between
311 two 'forkIO' threads.
312
313 Note in particular that the main program thread (the thread running
314 @Main.main@) is always a bound thread, so for good concurrency
315 performance you should ensure that the main thread is not doing
316 repeated communication with other threads in the system.  Typically
317 this means forking subthreads to do the work using 'forkIO', and
318 waiting for the results in the main thread.
319
320 -}
321
322 -- | 'True' if bound threads are supported.
323 -- If @rtsSupportsBoundThreads@ is 'False', 'isCurrentThreadBound'
324 -- will always return 'False' and both 'forkOS' and 'runInBoundThread' will
325 -- fail.
326 foreign import ccall rtsSupportsBoundThreads :: Bool
327
328
329 {- | 
330 Like 'forkIO', this sparks off a new thread to run the 'IO'
331 computation passed as the first argument, and returns the 'ThreadId'
332 of the newly created thread.
333
334 However, 'forkOS' creates a /bound/ thread, which is necessary if you
335 need to call foreign (non-Haskell) libraries that make use of
336 thread-local state, such as OpenGL (see "Control.Concurrent#boundthreads").
337
338 Using 'forkOS' instead of 'forkIO' makes no difference at all to the
339 scheduling behaviour of the Haskell runtime system.  It is a common
340 misconception that you need to use 'forkOS' instead of 'forkIO' to
341 avoid blocking all the Haskell threads when making a foreign call;
342 this isn't the case.  To allow foreign calls to be made without
343 blocking all the Haskell threads (with GHC), it is only necessary to
344 use the @-threaded@ option when linking your program, and to make sure
345 the foreign import is not marked @unsafe@.
346 -}
347
348 forkOS :: IO () -> IO ThreadId
349
350 foreign export ccall forkOS_entry
351     :: StablePtr (IO ()) -> IO ()
352
353 foreign import ccall "forkOS_entry" forkOS_entry_reimported
354     :: StablePtr (IO ()) -> IO ()
355
356 forkOS_entry :: StablePtr (IO ()) -> IO ()
357 forkOS_entry stableAction = do
358         action <- deRefStablePtr stableAction
359         action
360
361 foreign import ccall forkOS_createThread
362     :: StablePtr (IO ()) -> IO CInt
363
364 failNonThreaded :: IO a
365 failNonThreaded = fail $ "RTS doesn't support multiple OS threads "
366                        ++"(use ghc -threaded when linking)"
367
368 forkOS action0
369     | rtsSupportsBoundThreads = do
370         mv <- newEmptyMVar
371         b <- Exception.getMaskingState
372         let
373             -- async exceptions are masked in the child if they are masked
374             -- in the parent, as for forkIO (see #1048). forkOS_createThread
375             -- creates a thread with exceptions masked by default.
376             action1 = case b of
377                         Unmasked -> unsafeUnmask action0
378                         MaskedInterruptible -> action0
379                         MaskedUninterruptible -> uninterruptibleMask_ action0
380
381             action_plus = Exception.catch action1 childHandler
382
383         entry <- newStablePtr (myThreadId >>= putMVar mv >> action_plus)
384         err <- forkOS_createThread entry
385         when (err /= 0) $ fail "Cannot create OS thread."
386         tid <- takeMVar mv
387         freeStablePtr entry
388         return tid
389     | otherwise = failNonThreaded
390
391 -- | Returns 'True' if the calling thread is /bound/, that is, if it is
392 -- safe to use foreign libraries that rely on thread-local state from the
393 -- calling thread.
394 isCurrentThreadBound :: IO Bool
395 isCurrentThreadBound = IO $ \ s# ->
396     case isCurrentThreadBound# s# of
397         (# s2#, flg #) -> (# s2#, not (flg ==# 0#) #)
398
399
400 {- | 
401 Run the 'IO' computation passed as the first argument. If the calling thread
402 is not /bound/, a bound thread is created temporarily. @runInBoundThread@
403 doesn't finish until the 'IO' computation finishes.
404
405 You can wrap a series of foreign function calls that rely on thread-local state
406 with @runInBoundThread@ so that you can use them without knowing whether the
407 current thread is /bound/.
408 -}
409 runInBoundThread :: IO a -> IO a
410
411 runInBoundThread action
412     | rtsSupportsBoundThreads = do
413         bound <- isCurrentThreadBound
414         if bound
415             then action
416             else do
417                 ref <- newIORef undefined
418                 let action_plus = Exception.try action >>= writeIORef ref
419                 bracket (newStablePtr action_plus)
420                         freeStablePtr
421                         (\cEntry -> forkOS_entry_reimported cEntry >> readIORef ref) >>=
422                   unsafeResult
423     | otherwise = failNonThreaded
424
425 {- | 
426 Run the 'IO' computation passed as the first argument. If the calling thread
427 is /bound/, an unbound thread is created temporarily using 'forkIO'.
428 @runInBoundThread@ doesn't finish until the 'IO' computation finishes.
429
430 Use this function /only/ in the rare case that you have actually observed a
431 performance loss due to the use of bound threads. A program that
432 doesn't need it's main thread to be bound and makes /heavy/ use of concurrency
433 (e.g. a web server), might want to wrap it's @main@ action in
434 @runInUnboundThread@.
435
436 Note that exceptions which are thrown to the current thread are thrown in turn
437 to the thread that is executing the given computation. This ensures there's
438 always a way of killing the forked thread.
439 -}
440 runInUnboundThread :: IO a -> IO a
441
442 runInUnboundThread action = do
443   bound <- isCurrentThreadBound
444   if bound
445     then do
446       mv <- newEmptyMVar
447       mask $ \restore -> do
448         tid <- forkIO $ Exception.try (restore action) >>= putMVar mv
449         let wait = takeMVar mv `Exception.catch` \(e :: SomeException) ->
450                      Exception.throwTo tid e >> wait
451         wait >>= unsafeResult
452     else action
453
454 unsafeResult :: Either SomeException a -> IO a
455 unsafeResult = either Exception.throwIO return
456 #endif /* __GLASGOW_HASKELL__ */
457
458 #ifdef __GLASGOW_HASKELL__
459 -- ---------------------------------------------------------------------------
460 -- threadWaitRead/threadWaitWrite
461
462 -- | Block the current thread until data is available to read on the
463 -- given file descriptor (GHC only).
464 --
465 -- This will throw an 'IOError' if the file descriptor was closed
466 -- while this thread was blocked.  To safely close a file descriptor
467 -- that has been used with 'threadWaitRead', use
468 -- 'GHC.Conc.closeFdWith'.
469 threadWaitRead :: Fd -> IO ()
470 threadWaitRead fd
471 #ifdef mingw32_HOST_OS
472   -- we have no IO manager implementing threadWaitRead on Windows.
473   -- fdReady does the right thing, but we have to call it in a
474   -- separate thread, otherwise threadWaitRead won't be interruptible,
475   -- and this only works with -threaded.
476   | threaded  = withThread (waitFd fd 0)
477   | otherwise = case fd of
478                   0 -> do _ <- hWaitForInput stdin (-1)
479                           return ()
480                         -- hWaitForInput does work properly, but we can only
481                         -- do this for stdin since we know its FD.
482                   _ -> error "threadWaitRead requires -threaded on Windows, or use System.IO.hWaitForInput"
483 #else
484   = GHC.Conc.threadWaitRead fd
485 #endif
486
487 -- | Block the current thread until data can be written to the
488 -- given file descriptor (GHC only).
489 --
490 -- This will throw an 'IOError' if the file descriptor was closed
491 -- while this thread was blocked.  To safely close a file descriptor
492 -- that has been used with 'threadWaitWrite', use
493 -- 'GHC.Conc.closeFdWith'.
494 threadWaitWrite :: Fd -> IO ()
495 threadWaitWrite fd
496 #ifdef mingw32_HOST_OS
497   | threaded  = withThread (waitFd fd 1)
498   | otherwise = error "threadWaitWrite requires -threaded on Windows"
499 #else
500   = GHC.Conc.threadWaitWrite fd
501 #endif
502
503 #ifdef mingw32_HOST_OS
504 foreign import ccall unsafe "rtsSupportsBoundThreads" threaded :: Bool
505
506 withThread :: IO a -> IO a
507 withThread io = do
508   m <- newEmptyMVar
509   _ <- mask_ $ forkIO $ try io >>= putMVar m
510   x <- takeMVar m
511   case x of
512     Right a -> return a
513     Left e  -> throwIO (e :: IOException)
514
515 waitFd :: Fd -> CInt -> IO ()
516 waitFd fd write = do
517    throwErrnoIfMinus1_ "fdReady" $
518         fdReady (fromIntegral fd) write iNFINITE 0
519
520 iNFINITE :: CInt
521 iNFINITE = 0xFFFFFFFF -- urgh
522
523 foreign import ccall safe "fdReady"
524   fdReady :: CInt -> CInt -> CInt -> CInt -> IO CInt
525 #endif
526
527 -- ---------------------------------------------------------------------------
528 -- More docs
529
530 {- $osthreads
531
532       #osthreads# In GHC, threads created by 'forkIO' are lightweight threads, and
533       are managed entirely by the GHC runtime.  Typically Haskell
534       threads are an order of magnitude or two more efficient (in
535       terms of both time and space) than operating system threads.
536
537       The downside of having lightweight threads is that only one can
538       run at a time, so if one thread blocks in a foreign call, for
539       example, the other threads cannot continue.  The GHC runtime
540       works around this by making use of full OS threads where
541       necessary.  When the program is built with the @-threaded@
542       option (to link against the multithreaded version of the
543       runtime), a thread making a @safe@ foreign call will not block
544       the other threads in the system; another OS thread will take
545       over running Haskell threads until the original call returns.
546       The runtime maintains a pool of these /worker/ threads so that
547       multiple Haskell threads can be involved in external calls
548       simultaneously.
549
550       The "System.IO" library manages multiplexing in its own way.  On
551       Windows systems it uses @safe@ foreign calls to ensure that
552       threads doing I\/O operations don't block the whole runtime,
553       whereas on Unix systems all the currently blocked I\/O requests
554       are managed by a single thread (the /IO manager thread/) using
555       @select@.
556
557       The runtime will run a Haskell thread using any of the available
558       worker OS threads.  If you need control over which particular OS
559       thread is used to run a given Haskell thread, perhaps because
560       you need to call a foreign library that uses OS-thread-local
561       state, then you need bound threads (see "Control.Concurrent#boundthreads").
562
563       If you don't use the @-threaded@ option, then the runtime does
564       not make use of multiple OS threads.  Foreign calls will block
565       all other running Haskell threads until the call returns.  The
566       "System.IO" library still does multiplexing, so there can be multiple
567       threads doing I\/O, and this is handled internally by the runtime using
568       @select@.
569 -}
570
571 {- $termination
572
573       In a standalone GHC program, only the main thread is
574       required to terminate in order for the process to terminate.
575       Thus all other forked threads will simply terminate at the same
576       time as the main thread (the terminology for this kind of
577       behaviour is \"daemonic threads\").
578
579       If you want the program to wait for child threads to
580       finish before exiting, you need to program this yourself.  A
581       simple mechanism is to have each child thread write to an
582       'MVar' when it completes, and have the main
583       thread wait on all the 'MVar's before
584       exiting:
585
586 >   myForkIO :: IO () -> IO (MVar ())
587 >   myForkIO io = do
588 >     mvar <- newEmptyMVar
589 >     forkIO (io `finally` putMVar mvar ())
590 >     return mvar
591
592       Note that we use 'finally' from the
593       "Control.Exception" module to make sure that the
594       'MVar' is written to even if the thread dies or
595       is killed for some reason.
596
597       A better method is to keep a global list of all child
598       threads which we should wait for at the end of the program:
599
600 >    children :: MVar [MVar ()]
601 >    children = unsafePerformIO (newMVar [])
602 >    
603 >    waitForChildren :: IO ()
604 >    waitForChildren = do
605 >      cs <- takeMVar children
606 >      case cs of
607 >        []   -> return ()
608 >        m:ms -> do
609 >           putMVar children ms
610 >           takeMVar m
611 >           waitForChildren
612 >
613 >    forkChild :: IO () -> IO ThreadId
614 >    forkChild io = do
615 >        mvar <- newEmptyMVar
616 >        childs <- takeMVar children
617 >        putMVar children (mvar:childs)
618 >        forkIO (io `finally` putMVar mvar ())
619 >
620 >     main =
621 >       later waitForChildren $
622 >       ...
623
624       The main thread principle also applies to calls to Haskell from
625       outside, using @foreign export@.  When the @foreign export@ed
626       function is invoked, it starts a new main thread, and it returns
627       when this main thread terminates.  If the call causes new
628       threads to be forked, they may remain in the system after the
629       @foreign export@ed function has returned.
630 -}
631
632 {- $preemption
633
634       GHC implements pre-emptive multitasking: the execution of
635       threads are interleaved in a random fashion.  More specifically,
636       a thread may be pre-empted whenever it allocates some memory,
637       which unfortunately means that tight loops which do no
638       allocation tend to lock out other threads (this only seems to
639       happen with pathological benchmark-style code, however).
640
641       The rescheduling timer runs on a 20ms granularity by
642       default, but this may be altered using the
643       @-i\<n\>@ RTS option.  After a rescheduling
644       \"tick\" the running thread is pre-empted as soon as
645       possible.
646
647       One final note: the
648       @aaaa@ @bbbb@ example may not
649       work too well on GHC (see Scheduling, above), due
650       to the locking on a 'System.IO.Handle'.  Only one thread
651       may hold the lock on a 'System.IO.Handle' at any one
652       time, so if a reschedule happens while a thread is holding the
653       lock, the other thread won't be able to run.  The upshot is that
654       the switch from @aaaa@ to
655       @bbbbb@ happens infrequently.  It can be
656       improved by lowering the reschedule tick period.  We also have a
657       patch that causes a reschedule whenever a thread waiting on a
658       lock is woken up, but haven't found it to be useful for anything
659       other than this example :-)
660 -}
661 #endif /* __GLASGOW_HASKELL__ */