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