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