[project @ 2003-09-21 22:20:57 by wolfgang]
[haskell-directory.git] / Control / Concurrent.hs
1 -----------------------------------------------------------------------------
2 -- |
3 -- Module      :  Control.Concurrent
4 -- Copyright   :  (c) The University of Glasgow 2001
5 -- License     :  BSD-style (see the file libraries/base/LICENSE)
6 -- 
7 -- Maintainer  :  libraries@haskell.org
8 -- Stability   :  experimental
9 -- Portability :  non-portable (concurrency)
10 --
11 -- A common interface to a collection of useful concurrency
12 -- abstractions.
13 --
14 -----------------------------------------------------------------------------
15
16 module Control.Concurrent (
17         -- * Concurrent Haskell
18
19         -- $conc_intro
20
21         -- * Basic concurrency operations
22
23         ThreadId,
24 #ifdef __GLASGOW_HASKELL__
25         myThreadId,
26 #endif
27
28         forkIO,
29 #ifdef __GLASGOW_HASKELL__
30         killThread,
31         throwTo,
32 #endif
33
34         -- * Scheduling
35
36         -- $conc_scheduling     
37         yield,                  -- :: IO ()
38
39         -- ** Blocking
40         
41         -- $blocking
42
43 #ifdef __GLASGOW_HASKELL__
44         -- ** Waiting
45         threadDelay,            -- :: Int -> IO ()
46         threadWaitRead,         -- :: Int -> IO ()
47         threadWaitWrite,        -- :: Int -> IO ()
48 #endif
49
50         -- * Communication abstractions
51
52         module Control.Concurrent.MVar,
53         module Control.Concurrent.Chan,
54         module Control.Concurrent.QSem,
55         module Control.Concurrent.QSemN,
56         module Control.Concurrent.SampleVar,
57
58         -- * Merging of streams
59 #ifndef __HUGS__
60         mergeIO,                -- :: [a]   -> [a] -> IO [a]
61         nmergeIO,               -- :: [[a]] -> IO [a]
62 #endif
63         -- $merge
64
65         -- * Bound Threads
66         -- $boundthreads
67 #ifdef __GLASGOW_HASKELL__
68         rtsSupportsBoundThreads,
69         forkOS,
70         isCurrentThreadBound,
71         runInBoundThread
72 #endif
73
74         -- * GHC's implementation of concurrency
75
76         -- |This section describes features specific to GHC's
77         -- implementation of Concurrent Haskell.
78         
79         -- ** Terminating the program
80
81         -- $termination
82
83         -- ** Pre-emption
84
85         -- $preemption
86     ) where
87
88 import Prelude
89
90 import Control.Exception as Exception
91
92 #ifdef __GLASGOW_HASKELL__
93 import GHC.Conc
94 import GHC.TopHandler   ( reportStackOverflow, reportError )
95 import GHC.IOBase       ( IO(..) )
96 import GHC.IOBase       ( unsafeInterleaveIO )
97 import GHC.IOBase   ( newIORef, readIORef, writeIORef )
98 import GHC.Base
99
100 import Foreign.StablePtr
101 import Foreign.C.Types  ( CInt )
102 import Control.Monad    ( when )
103 #endif
104
105 #ifdef __HUGS__
106 import Hugs.ConcBase
107 #endif
108
109 import Control.Concurrent.MVar
110 import Control.Concurrent.Chan
111 import Control.Concurrent.QSem
112 import Control.Concurrent.QSemN
113 import Control.Concurrent.SampleVar
114
115 #ifdef __HUGS__
116 type ThreadId = ()
117 #endif
118
119 {- $conc_intro
120
121 The concurrency extension for Haskell is described in the paper
122 /Concurrent Haskell/
123 <http://www.haskell.org/ghc/docs/papers/concurrent-haskell.ps.gz>.
124
125 Concurrency is \"lightweight\", which means that both thread creation
126 and context switching overheads are extremely low.  Scheduling of
127 Haskell threads is done internally in the Haskell runtime system, and
128 doesn't make use of any operating system-supplied thread packages.
129
130 However, if you want to interact with a foreign library that expects your
131 program to use the operating system-supplied thread package, you can do so
132 by using 'forkOS' instead of 'forkIO'.
133
134 Haskell threads can communicate via 'MVar's, a kind of synchronised
135 mutable variable (see "Control.Concurrent.MVar").  Several common
136 concurrency abstractions can be built from 'MVar's, and these are
137 provided by the "Control.Concurrent" library.
138 In GHC, threads may also communicate via exceptions.
139 -}
140
141 {- $conc_scheduling
142
143     Scheduling may be either pre-emptive or co-operative,
144     depending on the implementation of Concurrent Haskell (see below
145     for imformation related to specific compilers).  In a co-operative
146     system, context switches only occur when you use one of the
147     primitives defined in this module.  This means that programs such
148     as:
149
150
151 >   main = forkIO (write 'a') >> write 'b'
152 >     where write c = putChar c >> write c
153
154     will print either @aaaaaaaaaaaaaa...@ or @bbbbbbbbbbbb...@,
155     instead of some random interleaving of @a@s and @b@s.  In
156     practice, cooperative multitasking is sufficient for writing
157     simple graphical user interfaces.  
158 -}
159
160 {- $blocking
161 Calling a foreign C procedure (such as @getchar@) that blocks waiting
162 for input will block /all/ threads, unless the @threadsafe@ attribute
163 is used on the foreign call (and your compiler \/ operating system
164 supports it).  GHC's I\/O system uses non-blocking I\/O internally to
165 implement thread-friendly I\/O, so calling standard Haskell I\/O
166 functions blocks only the thread making the call.
167 -}
168
169 -- Thread Ids, specifically the instances of Eq and Ord for these things.
170 -- The ThreadId type itself is defined in std/PrelConc.lhs.
171
172 -- Rather than define a new primitve, we use a little helper function
173 -- cmp_thread in the RTS.
174
175 #ifdef __GLASGOW_HASKELL__
176 id2TSO :: ThreadId -> ThreadId#
177 id2TSO (ThreadId t) = t
178
179 foreign import ccall unsafe "cmp_thread" cmp_thread :: ThreadId# -> ThreadId# -> Int
180 -- Returns -1, 0, 1
181
182 cmpThread :: ThreadId -> ThreadId -> Ordering
183 cmpThread t1 t2 = 
184    case cmp_thread (id2TSO t1) (id2TSO t2) of
185       -1 -> LT
186       0  -> EQ
187       _  -> GT -- must be 1
188
189 instance Eq ThreadId where
190    t1 == t2 = 
191       case t1 `cmpThread` t2 of
192          EQ -> True
193          _  -> False
194
195 instance Ord ThreadId where
196    compare = cmpThread
197
198 foreign import ccall unsafe "rts_getThreadId" getThreadId :: ThreadId# -> Int
199
200 instance Show ThreadId where
201    showsPrec d t = 
202         showString "ThreadId " . 
203         showsPrec d (getThreadId (id2TSO t))
204
205 {- |
206 This sparks off a new thread to run the 'IO' computation passed as the
207 first argument, and returns the 'ThreadId' of the newly created
208 thread.
209
210 The new thread will be a lightweight thread; if you want to use a foreign
211 library that uses thread-local storage, use 'forkOS' instead.
212 -}
213 forkIO :: IO () -> IO ThreadId
214 forkIO action = IO $ \ s -> 
215    case (fork# action_plus s) of (# s1, id #) -> (# s1, ThreadId id #)
216  where
217   action_plus = Exception.catch action childHandler
218
219 childHandler :: Exception -> IO ()
220 childHandler err = Exception.catch (real_handler err) childHandler
221
222 real_handler :: Exception -> IO ()
223 real_handler ex =
224   case ex of
225         -- ignore thread GC and killThread exceptions:
226         BlockedOnDeadMVar            -> return ()
227         AsyncException ThreadKilled  -> return ()
228
229         -- report all others:
230         AsyncException StackOverflow -> reportStackOverflow False
231         ErrorCall s -> reportError False s
232         other       -> reportError False (showsPrec 0 other "\n")
233
234 #endif /* __GLASGOW_HASKELL__ */
235
236 #ifndef __HUGS__
237 max_buff_size :: Int
238 max_buff_size = 1
239
240 mergeIO :: [a] -> [a] -> IO [a]
241 nmergeIO :: [[a]] -> IO [a]
242
243 -- $merge
244 -- The 'mergeIO' and 'nmergeIO' functions fork one thread for each
245 -- input list that concurrently evaluates that list; the results are
246 -- merged into a single output list.  
247 --
248 -- Note: Hugs does not provide these functions, since they require
249 -- preemptive multitasking.
250
251 mergeIO ls rs
252  = newEmptyMVar                >>= \ tail_node ->
253    newMVar tail_node           >>= \ tail_list ->
254    newQSem max_buff_size       >>= \ e ->
255    newMVar 2                   >>= \ branches_running ->
256    let
257     buff = (tail_list,e)
258    in
259     forkIO (suckIO branches_running buff ls) >>
260     forkIO (suckIO branches_running buff rs) >>
261     takeMVar tail_node  >>= \ val ->
262     signalQSem e        >>
263     return val
264
265 type Buffer a 
266  = (MVar (MVar [a]), QSem)
267
268 suckIO :: MVar Int -> Buffer a -> [a] -> IO ()
269
270 suckIO branches_running buff@(tail_list,e) vs
271  = case vs of
272         [] -> takeMVar branches_running >>= \ val ->
273               if val == 1 then
274                  takeMVar tail_list     >>= \ node ->
275                  putMVar node []        >>
276                  putMVar tail_list node
277               else      
278                  putMVar branches_running (val-1)
279         (x:xs) ->
280                 waitQSem e                       >>
281                 takeMVar tail_list               >>= \ node ->
282                 newEmptyMVar                     >>= \ next_node ->
283                 unsafeInterleaveIO (
284                         takeMVar next_node  >>= \ y ->
285                         signalQSem e        >>
286                         return y)                >>= \ next_node_val ->
287                 putMVar node (x:next_node_val)   >>
288                 putMVar tail_list next_node      >>
289                 suckIO branches_running buff xs
290
291 nmergeIO lss
292  = let
293     len = length lss
294    in
295     newEmptyMVar          >>= \ tail_node ->
296     newMVar tail_node     >>= \ tail_list ->
297     newQSem max_buff_size >>= \ e ->
298     newMVar len           >>= \ branches_running ->
299     let
300      buff = (tail_list,e)
301     in
302     mapIO (\ x -> forkIO (suckIO branches_running buff x)) lss >>
303     takeMVar tail_node  >>= \ val ->
304     signalQSem e        >>
305     return val
306   where
307     mapIO f xs = sequence (map f xs)
308 #endif /* __HUGS__ */
309
310 -- ---------------------------------------------------------------------------
311 -- Bound Threads
312
313 {- $boundthreads
314
315 Support for multiple operating system threads and bound threads as described
316 below is currently only available in the GHC runtime system when the runtime system
317 has been compiled using a special option.
318
319 When recompiling GHC, use ./configure --enable-threaded-rts to enable this.
320 To find your GHC has already been compiled that way, use
321 'rtsSupportsBoundThreads' from GHCi.
322
323 Other Haskell systems do not currently support multiple operating system threads.
324
325 A bound thread is a haskell thread that is /bound/ to an operating system
326 thread. While the bound thread is still scheduled by the Haskell run-time
327 system, the operating system thread takes care of all the foreign calls made
328 by the bound thread.
329
330 To a foreign library, the bound thread will look exactly like an ordinary
331 operating system thread created using OS functions like @pthread_create@
332 or @CreateThread@.
333
334 Bound threads can be created using the 'forkOS' function below. All foreign
335 exported functions are run in a bound thread (bound to the OS thread that
336 called the function). Also, the @main@ action of every Haskell program is
337 run in a bound thread.
338
339 Why do we need this? Because if a foreign library is called from a thread
340 created using 'forkIO', it won't have access to any /thread-local state/ - 
341 state variables that have specific values for each OS thread
342 (see POSIX's @pthread_key_create@ or Win32's @TlsAlloc@). Therefore, some
343 libraries (OpenGL, for example) will not work from a thread created using
344 'forkIO'. They work fine in threads created using 'forkOS' or when called
345 from @main@ or from a @foreign export@.
346 -}
347
348 #ifdef
349  __GLASGOW_HASKELL__
350
351 -- | 'True' if bound threads are supported.
352 -- If @rtsSupportsBoundThreads@ is 'False', 'isCurrentThreadBound'
353 -- will always return 'False' and both 'forkOS' and 'runInBoundThread' will
354 -- fail.
355 foreign import ccall rtsSupportsBoundThreads :: Bool
356
357
358 {- |
359 Like 'forkIO', this sparks off a new thread to run the 'IO' computation passed as the
360 first argument, and returns the 'ThreadId' of the newly created
361 thread.
362
363 However, @forkOS@ uses operating system-supplied multithreading support to create
364 a new operating system thread. The new thread is /bound/, which means that
365 all foreign calls made by the 'IO' computation are guaranteed to be executed
366 in this new operating system thread; also, the operating system thread is not
367 used for any other foreign calls.
368
369 This means that you can use all kinds of foreign libraries from this thread 
370 (even those that rely on thread-local state), without the limitations of 'forkIO'.
371 -}
372 forkOS :: IO () -> IO ThreadId
373
374 foreign export ccall forkOS_entry
375     :: StablePtr (IO ()) -> IO ()
376
377 foreign import ccall "forkOS_entry" forkOS_entry_reimported
378     :: StablePtr (IO ()) -> IO ()
379
380 forkOS_entry stableAction = do
381         action <- deRefStablePtr stableAction
382         action
383
384 foreign import ccall forkOS_createThread
385     :: StablePtr (IO ()) -> IO CInt
386
387 forkOS action 
388     | rtsSupportsBoundThreads = do
389         mv <- newEmptyMVar
390         let action_plus = Exception.catch action childHandler
391         entry <- newStablePtr (myThreadId >>= putMVar mv >> action_plus)
392         err <- forkOS_createThread entry
393         when (err /= 0) $ fail "Cannot create OS thread."
394         tid <- takeMVar mv
395         freeStablePtr entry
396         return tid
397     | otherwise = fail "RTS not built to support multiple OS threads."
398
399 -- | Returns 'True' if the calling thread is /bound/, that is, if it is
400 -- safe to use foreign libraries that rely on thread-local state from the
401 -- calling thread.
402 isCurrentThreadBound :: IO Bool
403 isCurrentThreadBound = IO $ \ s# -> 
404     case isCurrentThreadBound# s# of
405         (# s2#, flg #) -> (# s2#, not (flg ==# 0#) #)
406
407
408 {- | 
409 Run the 'IO' computation passed as the first argument. If the calling thread
410 is not /bound/, a bound thread is created temporarily. @runInBoundThread@
411 doesn't finish until the 'IO' computation finishes.
412
413 You can wrap a series of foreign function calls that rely on thread-local state
414 with @runInBoundThread@ so that you can use them without knowing whether the
415 current thread is /bound/.
416 -}
417 runInBoundThread :: IO a -> IO a
418
419 runInBoundThread action
420     | rtsSupportsBoundThreads = do
421         bound <- isCurrentThreadBound
422         if bound
423             then action
424             else do
425                 ref <- newIORef undefined
426                 let action_plus = Exception.try action >>= writeIORef ref
427                 resultOrException <- 
428                     bracket (newStablePtr action_plus)
429                             freeStablePtr
430                             (\cEntry -> forkOS_entry_reimported cEntry >> readIORef ref)
431                 case resultOrException of
432                     Left exception -> Exception.throw exception
433                     Right result -> return result
434     | otherwise = fail "RTS not built to support multiple OS threads."
435
436 {- | 
437 Run the 'IO' computation passed as the first argument. If the calling thread
438 is /bound/, an unbound thread is created temporarily using 'forkIO'.
439 @runInBoundThread@ doesn't finish until the 'IO' computation finishes.
440
441 Use this function /only/ in the rare case that you have actually observed a
442 performance loss due to the use of bound threads. A program that
443 doesn't need it's main thread to be bound and makes /heavy/ use of concurrency
444 (e.g. a web server), might want to wrap it's @main@ action in
445 @runInUnboundThread@.
446 -}
447 runInUnboundThread :: IO a -> IO a
448
449 runInUnboundThread action = do
450         bound <- isCurrentThreadBound
451         if bound
452                 then do
453                         mv <- newEmptyMVar
454                         forkIO (E.try action >>= putMVar mv)
455                         takeMVar mv >>= \either -> case either of
456                         Left exception -> E.throw exception
457                         Right result -> return result
458                 else action
459         
460 #endif
461
462 -- ---------------------------------------------------------------------------
463 -- More docs
464
465 {- $termination
466
467       In a standalone GHC program, only the main thread is
468       required to terminate in order for the process to terminate.
469       Thus all other forked threads will simply terminate at the same
470       time as the main thread (the terminology for this kind of
471       behaviour is \"daemonic threads\").
472
473       If you want the program to wait for child threads to
474       finish before exiting, you need to program this yourself.  A
475       simple mechanism is to have each child thread write to an
476       'MVar' when it completes, and have the main
477       thread wait on all the 'MVar's before
478       exiting:
479
480 >   myForkIO :: IO () -> IO (MVar ())
481 >   myForkIO io = do
482 >     mvar \<- newEmptyMVar
483 >     forkIO (io \`finally\` putMVar mvar ())
484 >     return mvar
485
486       Note that we use 'finally' from the
487       "Control.Exception" module to make sure that the
488       'MVar' is written to even if the thread dies or
489       is killed for some reason.
490
491       A better method is to keep a global list of all child
492       threads which we should wait for at the end of the program:
493
494 >     children :: MVar [MVar ()]
495 >     children = unsafePerformIO (newMVar [])
496 >     
497 >     waitForChildren :: IO ()
498 >     waitForChildren = do
499 >       (mvar:mvars) \<- takeMVar children
500 >       putMVar children mvars
501 >       takeMVar mvar
502 >       waitForChildren
503 >     
504 >     forkChild :: IO () -> IO ()
505 >     forkChild io = do
506 >        mvar \<- newEmptyMVar
507 >        forkIO (p \`finally\` putMVar mvar ())
508 >        childs \<- takeMVar children
509 >        putMVar children (mvar:childs)
510 >     
511 >     later = flip finally
512 >     
513 >     main =
514 >       later waitForChildren $
515 >       ...
516
517       The main thread principle also applies to calls to Haskell from
518       outside, using @foreign export@.  When the @foreign export@ed
519       function is invoked, it starts a new main thread, and it returns
520       when this main thread terminates.  If the call causes new
521       threads to be forked, they may remain in the system after the
522       @foreign export@ed function has returned.
523 -}
524
525 {- $preemption
526
527       GHC implements pre-emptive multitasking: the execution of
528       threads are interleaved in a random fashion.  More specifically,
529       a thread may be pre-empted whenever it allocates some memory,
530       which unfortunately means that tight loops which do no
531       allocation tend to lock out other threads (this only seems to
532       happen with pathalogical benchmark-style code, however).
533
534       The rescheduling timer runs on a 20ms granularity by
535       default, but this may be altered using the
536       @-i\<n\>@ RTS option.  After a rescheduling
537       \"tick\" the running thread is pre-empted as soon as
538       possible.
539
540       One final note: the
541       @aaaa@ @bbbb@ example may not
542       work too well on GHC (see Scheduling, above), due
543       to the locking on a 'System.IO.Handle'.  Only one thread
544       may hold the lock on a 'System.IO.Handle' at any one
545       time, so if a reschedule happens while a thread is holding the
546       lock, the other thread won't be able to run.  The upshot is that
547       the switch from @aaaa@ to
548       @bbbbb@ happens infrequently.  It can be
549       improved by lowering the reschedule tick period.  We also have a
550       patch that causes a reschedule whenever a thread waiting on a
551       lock is woken up, but haven't found it to be useful for anything
552       other than this example :-)
553 -}