1 {-# OPTIONS_GHC -fno-warn-unused-imports #-}
2 -----------------------------------------------------------------------------
4 -- Module : Control.Concurrent
5 -- Copyright : (c) The University of Glasgow 2001
6 -- License : BSD-style (see the file libraries/base/LICENSE)
8 -- Maintainer : libraries@haskell.org
9 -- Stability : experimental
10 -- Portability : non-portable (concurrency)
12 -- A common interface to a collection of useful concurrency
15 -----------------------------------------------------------------------------
17 module Control.Concurrent (
18 -- * Concurrent Haskell
22 -- * Basic concurrency operations
25 #ifdef __GLASGOW_HASKELL__
30 #ifdef __GLASGOW_HASKELL__
44 #ifdef __GLASGOW_HASKELL__
46 threadDelay, -- :: Int -> IO ()
47 threadWaitRead, -- :: Int -> IO ()
48 threadWaitWrite, -- :: Int -> IO ()
51 -- * Communication abstractions
53 module Control.Concurrent.MVar,
54 module Control.Concurrent.Chan,
55 module Control.Concurrent.QSem,
56 module Control.Concurrent.QSemN,
57 module Control.Concurrent.SampleVar,
59 -- * Merging of streams
61 mergeIO, -- :: [a] -> [a] -> IO [a]
62 nmergeIO, -- :: [[a]] -> IO [a]
66 #ifdef __GLASGOW_HASKELL__
69 rtsSupportsBoundThreads,
76 -- * GHC's implementation of concurrency
78 -- |This section describes features specific to GHC's
79 -- implementation of Concurrent Haskell.
81 -- ** Haskell threads and Operating System threads
85 -- ** Terminating the program
96 import Control.Exception.Base as Exception
98 #ifdef __GLASGOW_HASKELL__
100 import GHC.Conc ( ThreadId(..), myThreadId, killThread, yield,
101 threadDelay, forkIO, childHandler )
102 import qualified GHC.Conc
103 import GHC.IO ( IO(..), unsafeInterleaveIO )
104 import GHC.IORef ( newIORef, readIORef, writeIORef )
107 import System.Posix.Types ( Fd )
108 import Foreign.StablePtr
109 import Foreign.C.Types ( CInt )
110 import Control.Monad ( when )
112 #ifdef mingw32_HOST_OS
122 import Control.Concurrent.MVar
123 import Control.Concurrent.Chan
124 import Control.Concurrent.QSem
125 import Control.Concurrent.QSemN
126 import Control.Concurrent.SampleVar
134 The concurrency extension for Haskell is described in the paper
136 <http://www.haskell.org/ghc/docs/papers/concurrent-haskell.ps.gz>.
138 Concurrency is \"lightweight\", which means that both thread creation
139 and context switching overheads are extremely low. Scheduling of
140 Haskell threads is done internally in the Haskell runtime system, and
141 doesn't make use of any operating system-supplied thread packages.
143 However, if you want to interact with a foreign library that expects your
144 program to use the operating system-supplied thread package, you can do so
145 by using 'forkOS' instead of 'forkIO'.
147 Haskell threads can communicate via 'MVar's, a kind of synchronised
148 mutable variable (see "Control.Concurrent.MVar"). Several common
149 concurrency abstractions can be built from 'MVar's, and these are
150 provided by the "Control.Concurrent" library.
151 In GHC, threads may also communicate via exceptions.
156 Scheduling may be either pre-emptive or co-operative,
157 depending on the implementation of Concurrent Haskell (see below
158 for information related to specific compilers). In a co-operative
159 system, context switches only occur when you use one of the
160 primitives defined in this module. This means that programs such
164 > main = forkIO (write 'a') >> write 'b'
165 > where write c = putChar c >> write c
167 will print either @aaaaaaaaaaaaaa...@ or @bbbbbbbbbbbb...@,
168 instead of some random interleaving of @a@s and @b@s. In
169 practice, cooperative multitasking is sufficient for writing
170 simple graphical user interfaces.
174 Different Haskell implementations have different characteristics with
175 regard to which operations block /all/ threads.
177 Using GHC without the @-threaded@ option, all foreign calls will block
178 all other Haskell threads in the system, although I\/O operations will
179 not. With the @-threaded@ option, only foreign calls with the @unsafe@
180 attribute will block all other threads.
182 Using Hugs, all I\/O operations and foreign calls will block all other
190 mergeIO :: [a] -> [a] -> IO [a]
191 nmergeIO :: [[a]] -> IO [a]
194 -- The 'mergeIO' and 'nmergeIO' functions fork one thread for each
195 -- input list that concurrently evaluates that list; the results are
196 -- merged into a single output list.
198 -- Note: Hugs does not provide these functions, since they require
199 -- preemptive multitasking.
202 = newEmptyMVar >>= \ tail_node ->
203 newMVar tail_node >>= \ tail_list ->
204 newQSem max_buff_size >>= \ e ->
205 newMVar 2 >>= \ branches_running ->
209 forkIO (suckIO branches_running buff ls) >>
210 forkIO (suckIO branches_running buff rs) >>
211 takeMVar tail_node >>= \ val ->
216 = (MVar (MVar [a]), QSem)
218 suckIO :: MVar Int -> Buffer a -> [a] -> IO ()
220 suckIO branches_running buff@(tail_list,e) vs
222 [] -> takeMVar branches_running >>= \ val ->
224 takeMVar tail_list >>= \ node ->
226 putMVar tail_list node
228 putMVar branches_running (val-1)
231 takeMVar tail_list >>= \ node ->
232 newEmptyMVar >>= \ next_node ->
234 takeMVar next_node >>= \ y ->
236 return y) >>= \ next_node_val ->
237 putMVar node (x:next_node_val) >>
238 putMVar tail_list next_node >>
239 suckIO branches_running buff xs
245 newEmptyMVar >>= \ tail_node ->
246 newMVar tail_node >>= \ tail_list ->
247 newQSem max_buff_size >>= \ e ->
248 newMVar len >>= \ branches_running ->
252 mapIO (\ x -> forkIO (suckIO branches_running buff x)) lss >>
253 takeMVar tail_node >>= \ val ->
257 mapIO f xs = sequence (map f xs)
258 #endif /* __HUGS__ */
260 #ifdef __GLASGOW_HASKELL__
261 -- ---------------------------------------------------------------------------
267 Support for multiple operating system threads and bound threads as described
268 below is currently only available in the GHC runtime system if you use the
269 /-threaded/ option when linking.
271 Other Haskell systems do not currently support multiple operating system threads.
273 A bound thread is a haskell thread that is /bound/ to an operating system
274 thread. While the bound thread is still scheduled by the Haskell run-time
275 system, the operating system thread takes care of all the foreign calls made
278 To a foreign library, the bound thread will look exactly like an ordinary
279 operating system thread created using OS functions like @pthread_create@
282 Bound threads can be created using the 'forkOS' function below. All foreign
283 exported functions are run in a bound thread (bound to the OS thread that
284 called the function). Also, the @main@ action of every Haskell program is
285 run in a bound thread.
287 Why do we need this? Because if a foreign library is called from a thread
288 created using 'forkIO', it won't have access to any /thread-local state/ -
289 state variables that have specific values for each OS thread
290 (see POSIX's @pthread_key_create@ or Win32's @TlsAlloc@). Therefore, some
291 libraries (OpenGL, for example) will not work from a thread created using
292 'forkIO'. They work fine in threads created using 'forkOS' or when called
293 from @main@ or from a @foreign export@.
295 In terms of performance, 'forkOS' (aka bound) threads are much more
296 expensive than 'forkIO' (aka unbound) threads, because a 'forkOS'
297 thread is tied to a particular OS thread, whereas a 'forkIO' thread
298 can be run by any OS thread. Context-switching between a 'forkOS'
299 thread and a 'forkIO' thread is many times more expensive than between
300 two 'forkIO' threads.
302 Note in particular that the main program thread (the thread running
303 @Main.main@) is always a bound thread, so for good concurrency
304 performance you should ensure that the main thread is not doing
305 repeated communication with other threads in the system. Typically
306 this means forking subthreads to do the work using 'forkIO', and
307 waiting for the results in the main thread.
311 -- | 'True' if bound threads are supported.
312 -- If @rtsSupportsBoundThreads@ is 'False', 'isCurrentThreadBound'
313 -- will always return 'False' and both 'forkOS' and 'runInBoundThread' will
315 foreign import ccall rtsSupportsBoundThreads :: Bool
319 Like 'forkIO', this sparks off a new thread to run the 'IO'
320 computation passed as the first argument, and returns the 'ThreadId'
321 of the newly created thread.
323 However, 'forkOS' creates a /bound/ thread, which is necessary if you
324 need to call foreign (non-Haskell) libraries that make use of
325 thread-local state, such as OpenGL (see "Control.Concurrent#boundthreads").
327 Using 'forkOS' instead of 'forkIO' makes no difference at all to the
328 scheduling behaviour of the Haskell runtime system. It is a common
329 misconception that you need to use 'forkOS' instead of 'forkIO' to
330 avoid blocking all the Haskell threads when making a foreign call;
331 this isn't the case. To allow foreign calls to be made without
332 blocking all the Haskell threads (with GHC), it is only necessary to
333 use the @-threaded@ option when linking your program, and to make sure
334 the foreign import is not marked @unsafe@.
337 forkOS :: IO () -> IO ThreadId
339 foreign export ccall forkOS_entry
340 :: StablePtr (IO ()) -> IO ()
342 foreign import ccall "forkOS_entry" forkOS_entry_reimported
343 :: StablePtr (IO ()) -> IO ()
345 forkOS_entry :: StablePtr (IO ()) -> IO ()
346 forkOS_entry stableAction = do
347 action <- deRefStablePtr stableAction
350 foreign import ccall forkOS_createThread
351 :: StablePtr (IO ()) -> IO CInt
353 failNonThreaded :: IO a
354 failNonThreaded = fail $ "RTS doesn't support multiple OS threads "
355 ++"(use ghc -threaded when linking)"
358 | rtsSupportsBoundThreads = do
360 b <- Exception.blocked
362 -- async exceptions are blocked in the child if they are blocked
363 -- in the parent, as for forkIO (see #1048). forkOS_createThread
364 -- creates a thread with exceptions blocked by default.
365 action1 | b = action0
366 | otherwise = unblock action0
368 action_plus = Exception.catch action1 childHandler
370 entry <- newStablePtr (myThreadId >>= putMVar mv >> action_plus)
371 err <- forkOS_createThread entry
372 when (err /= 0) $ fail "Cannot create OS thread."
376 | otherwise = failNonThreaded
378 -- | Returns 'True' if the calling thread is /bound/, that is, if it is
379 -- safe to use foreign libraries that rely on thread-local state from the
381 isCurrentThreadBound :: IO Bool
382 isCurrentThreadBound = IO $ \ s# ->
383 case isCurrentThreadBound# s# of
384 (# s2#, flg #) -> (# s2#, not (flg ==# 0#) #)
388 Run the 'IO' computation passed as the first argument. If the calling thread
389 is not /bound/, a bound thread is created temporarily. @runInBoundThread@
390 doesn't finish until the 'IO' computation finishes.
392 You can wrap a series of foreign function calls that rely on thread-local state
393 with @runInBoundThread@ so that you can use them without knowing whether the
394 current thread is /bound/.
396 runInBoundThread :: IO a -> IO a
398 runInBoundThread action
399 | rtsSupportsBoundThreads = do
400 bound <- isCurrentThreadBound
404 ref <- newIORef undefined
405 let action_plus = Exception.try action >>= writeIORef ref
407 bracket (newStablePtr action_plus)
409 (\cEntry -> forkOS_entry_reimported cEntry >> readIORef ref)
410 case resultOrException of
411 Left exception -> Exception.throw (exception :: SomeException)
412 Right result -> return result
413 | otherwise = failNonThreaded
416 Run the 'IO' computation passed as the first argument. If the calling thread
417 is /bound/, an unbound thread is created temporarily using 'forkIO'.
418 @runInBoundThread@ doesn't finish until the 'IO' computation finishes.
420 Use this function /only/ in the rare case that you have actually observed a
421 performance loss due to the use of bound threads. A program that
422 doesn't need it's main thread to be bound and makes /heavy/ use of concurrency
423 (e.g. a web server), might want to wrap it's @main@ action in
424 @runInUnboundThread@.
426 runInUnboundThread :: IO a -> IO a
428 runInUnboundThread action = do
429 bound <- isCurrentThreadBound
434 _ <- block $ forkIO $
435 Exception.try (if b then action else unblock action) >>=
437 takeMVar mv >>= \ei -> case ei of
438 Left exception -> Exception.throw (exception :: SomeException)
439 Right result -> return result
442 #endif /* __GLASGOW_HASKELL__ */
444 #ifdef __GLASGOW_HASKELL__
445 -- ---------------------------------------------------------------------------
446 -- threadWaitRead/threadWaitWrite
448 -- | Block the current thread until data is available to read on the
449 -- given file descriptor (GHC only).
450 threadWaitRead :: Fd -> IO ()
452 #ifdef mingw32_HOST_OS
453 -- we have no IO manager implementing threadWaitRead on Windows.
454 -- fdReady does the right thing, but we have to call it in a
455 -- separate thread, otherwise threadWaitRead won't be interruptible,
456 -- and this only works with -threaded.
457 | threaded = withThread (waitFd fd 0)
458 | otherwise = case fd of
459 0 -> do _ <- hWaitForInput stdin (-1)
461 -- hWaitForInput does work properly, but we can only
462 -- do this for stdin since we know its FD.
463 _ -> error "threadWaitRead requires -threaded on Windows, or use System.IO.hWaitForInput"
465 = GHC.Conc.threadWaitRead fd
468 -- | Block the current thread until data can be written to the
469 -- given file descriptor (GHC only).
470 threadWaitWrite :: Fd -> IO ()
472 #ifdef mingw32_HOST_OS
473 | threaded = withThread (waitFd fd 1)
474 | otherwise = error "threadWaitWrite requires -threaded on Windows"
476 = GHC.Conc.threadWaitWrite fd
479 #ifdef mingw32_HOST_OS
480 foreign import ccall unsafe "rtsSupportsBoundThreads" threaded :: Bool
482 withThread :: IO a -> IO a
485 _ <- block $ forkIO $ try io >>= putMVar m
489 Left e -> throwIO (e :: IOException)
491 waitFd :: Fd -> CInt -> IO ()
493 throwErrnoIfMinus1_ "fdReady" $
494 fdReady (fromIntegral fd) write (fromIntegral iNFINITE) 0
497 iNFINITE = 0xFFFFFFFF -- urgh
499 foreign import ccall safe "fdReady"
500 fdReady :: CInt -> CInt -> CInt -> CInt -> IO CInt
503 -- ---------------------------------------------------------------------------
508 #osthreads# In GHC, threads created by 'forkIO' are lightweight threads, and
509 are managed entirely by the GHC runtime. Typically Haskell
510 threads are an order of magnitude or two more efficient (in
511 terms of both time and space) than operating system threads.
513 The downside of having lightweight threads is that only one can
514 run at a time, so if one thread blocks in a foreign call, for
515 example, the other threads cannot continue. The GHC runtime
516 works around this by making use of full OS threads where
517 necessary. When the program is built with the @-threaded@
518 option (to link against the multithreaded version of the
519 runtime), a thread making a @safe@ foreign call will not block
520 the other threads in the system; another OS thread will take
521 over running Haskell threads until the original call returns.
522 The runtime maintains a pool of these /worker/ threads so that
523 multiple Haskell threads can be involved in external calls
526 The "System.IO" library manages multiplexing in its own way. On
527 Windows systems it uses @safe@ foreign calls to ensure that
528 threads doing I\/O operations don't block the whole runtime,
529 whereas on Unix systems all the currently blocked I\/O requests
530 are managed by a single thread (the /IO manager thread/) using
533 The runtime will run a Haskell thread using any of the available
534 worker OS threads. If you need control over which particular OS
535 thread is used to run a given Haskell thread, perhaps because
536 you need to call a foreign library that uses OS-thread-local
537 state, then you need bound threads (see "Control.Concurrent#boundthreads").
539 If you don't use the @-threaded@ option, then the runtime does
540 not make use of multiple OS threads. Foreign calls will block
541 all other running Haskell threads until the call returns. The
542 "System.IO" library still does multiplexing, so there can be multiple
543 threads doing I\/O, and this is handled internally by the runtime using
549 In a standalone GHC program, only the main thread is
550 required to terminate in order for the process to terminate.
551 Thus all other forked threads will simply terminate at the same
552 time as the main thread (the terminology for this kind of
553 behaviour is \"daemonic threads\").
555 If you want the program to wait for child threads to
556 finish before exiting, you need to program this yourself. A
557 simple mechanism is to have each child thread write to an
558 'MVar' when it completes, and have the main
559 thread wait on all the 'MVar's before
562 > myForkIO :: IO () -> IO (MVar ())
564 > mvar <- newEmptyMVar
565 > forkIO (io `finally` putMVar mvar ())
568 Note that we use 'finally' from the
569 "Control.Exception" module to make sure that the
570 'MVar' is written to even if the thread dies or
571 is killed for some reason.
573 A better method is to keep a global list of all child
574 threads which we should wait for at the end of the program:
576 > children :: MVar [MVar ()]
577 > children = unsafePerformIO (newMVar [])
579 > waitForChildren :: IO ()
580 > waitForChildren = do
581 > cs <- takeMVar children
585 > putMVar children ms
589 > forkChild :: IO () -> IO ThreadId
591 > mvar <- newEmptyMVar
592 > childs <- takeMVar children
593 > putMVar children (mvar:childs)
594 > forkIO (io `finally` putMVar mvar ())
597 > later waitForChildren $
600 The main thread principle also applies to calls to Haskell from
601 outside, using @foreign export@. When the @foreign export@ed
602 function is invoked, it starts a new main thread, and it returns
603 when this main thread terminates. If the call causes new
604 threads to be forked, they may remain in the system after the
605 @foreign export@ed function has returned.
610 GHC implements pre-emptive multitasking: the execution of
611 threads are interleaved in a random fashion. More specifically,
612 a thread may be pre-empted whenever it allocates some memory,
613 which unfortunately means that tight loops which do no
614 allocation tend to lock out other threads (this only seems to
615 happen with pathological benchmark-style code, however).
617 The rescheduling timer runs on a 20ms granularity by
618 default, but this may be altered using the
619 @-i\<n\>@ RTS option. After a rescheduling
620 \"tick\" the running thread is pre-empted as soon as
624 @aaaa@ @bbbb@ example may not
625 work too well on GHC (see Scheduling, above), due
626 to the locking on a 'System.IO.Handle'. Only one thread
627 may hold the lock on a 'System.IO.Handle' at any one
628 time, so if a reschedule happens while a thread is holding the
629 lock, the other thread won't be able to run. The upshot is that
630 the switch from @aaaa@ to
631 @bbbbb@ happens infrequently. It can be
632 improved by lowering the reschedule tick period. We also have a
633 patch that causes a reschedule whenever a thread waiting on a
634 lock is woken up, but haven't found it to be useful for anything
635 other than this example :-)
637 #endif /* __GLASGOW_HASKELL__ */