1 -----------------------------------------------------------------------------
3 -- Module : Control.Concurrent
4 -- Copyright : (c) The University of Glasgow 2001
5 -- License : BSD-style (see the file libraries/base/LICENSE)
7 -- Maintainer : libraries@haskell.org
8 -- Stability : experimental
9 -- Portability : non-portable (concurrency)
11 -- A common interface to a collection of useful concurrency
14 -----------------------------------------------------------------------------
16 module Control.Concurrent (
17 -- * Concurrent Haskell
21 -- * Basic concurrency operations
24 #ifdef __GLASGOW_HASKELL__
29 #ifdef __GLASGOW_HASKELL__
43 #ifdef __GLASGOW_HASKELL__
45 threadDelay, -- :: Int -> IO ()
46 threadWaitRead, -- :: Int -> IO ()
47 threadWaitWrite, -- :: Int -> IO ()
50 -- * Communication abstractions
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,
58 -- * Merging of streams
60 mergeIO, -- :: [a] -> [a] -> IO [a]
61 nmergeIO, -- :: [[a]] -> IO [a]
65 #ifdef __GLASGOW_HASKELL__
68 rtsSupportsBoundThreads,
75 -- * GHC's implementation of concurrency
77 -- |This section describes features specific to GHC's
78 -- implementation of Concurrent Haskell.
80 -- ** Haskell threads and Operating System threads
84 -- ** Terminating the program
95 import Control.Exception as Exception
97 #ifdef __GLASGOW_HASKELL__
98 import GHC.Conc ( ThreadId(..), myThreadId, killThread, yield,
99 threadDelay, forkIO, childHandler )
100 import qualified GHC.Conc
101 import GHC.TopHandler ( reportStackOverflow, reportError )
102 import GHC.IOBase ( IO(..) )
103 import GHC.IOBase ( unsafeInterleaveIO )
104 import GHC.IOBase ( 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
123 import Control.Concurrent.MVar
124 import Control.Concurrent.Chan
125 import Control.Concurrent.QSem
126 import Control.Concurrent.QSemN
127 import Control.Concurrent.SampleVar
135 The concurrency extension for Haskell is described in the paper
137 <http://www.haskell.org/ghc/docs/papers/concurrent-haskell.ps.gz>.
139 Concurrency is \"lightweight\", which means that both thread creation
140 and context switching overheads are extremely low. Scheduling of
141 Haskell threads is done internally in the Haskell runtime system, and
142 doesn't make use of any operating system-supplied thread packages.
144 However, if you want to interact with a foreign library that expects your
145 program to use the operating system-supplied thread package, you can do so
146 by using 'forkOS' instead of 'forkIO'.
148 Haskell threads can communicate via 'MVar's, a kind of synchronised
149 mutable variable (see "Control.Concurrent.MVar"). Several common
150 concurrency abstractions can be built from 'MVar's, and these are
151 provided by the "Control.Concurrent" library.
152 In GHC, threads may also communicate via exceptions.
157 Scheduling may be either pre-emptive or co-operative,
158 depending on the implementation of Concurrent Haskell (see below
159 for information related to specific compilers). In a co-operative
160 system, context switches only occur when you use one of the
161 primitives defined in this module. This means that programs such
165 > main = forkIO (write 'a') >> write 'b'
166 > where write c = putChar c >> write c
168 will print either @aaaaaaaaaaaaaa...@ or @bbbbbbbbbbbb...@,
169 instead of some random interleaving of @a@s and @b@s. In
170 practice, cooperative multitasking is sufficient for writing
171 simple graphical user interfaces.
175 Different Haskell implementations have different characteristics with
176 regard to which operations block /all/ threads.
178 Using GHC without the @-threaded@ option, all foreign calls will block
179 all other Haskell threads in the system, although I\/O operations will
180 not. With the @-threaded@ option, only foreign calls with the @unsafe@
181 attribute will block all other threads.
183 Using Hugs, all I\/O operations and foreign calls will block all other
191 mergeIO :: [a] -> [a] -> IO [a]
192 nmergeIO :: [[a]] -> IO [a]
195 -- The 'mergeIO' and 'nmergeIO' functions fork one thread for each
196 -- input list that concurrently evaluates that list; the results are
197 -- merged into a single output list.
199 -- Note: Hugs does not provide these functions, since they require
200 -- preemptive multitasking.
203 = newEmptyMVar >>= \ tail_node ->
204 newMVar tail_node >>= \ tail_list ->
205 newQSem max_buff_size >>= \ e ->
206 newMVar 2 >>= \ branches_running ->
210 forkIO (suckIO branches_running buff ls) >>
211 forkIO (suckIO branches_running buff rs) >>
212 takeMVar tail_node >>= \ val ->
217 = (MVar (MVar [a]), QSem)
219 suckIO :: MVar Int -> Buffer a -> [a] -> IO ()
221 suckIO branches_running buff@(tail_list,e) vs
223 [] -> takeMVar branches_running >>= \ val ->
225 takeMVar tail_list >>= \ node ->
227 putMVar tail_list node
229 putMVar branches_running (val-1)
232 takeMVar tail_list >>= \ node ->
233 newEmptyMVar >>= \ next_node ->
235 takeMVar next_node >>= \ y ->
237 return y) >>= \ next_node_val ->
238 putMVar node (x:next_node_val) >>
239 putMVar tail_list next_node >>
240 suckIO branches_running buff xs
246 newEmptyMVar >>= \ tail_node ->
247 newMVar tail_node >>= \ tail_list ->
248 newQSem max_buff_size >>= \ e ->
249 newMVar len >>= \ branches_running ->
253 mapIO (\ x -> forkIO (suckIO branches_running buff x)) lss >>
254 takeMVar tail_node >>= \ val ->
258 mapIO f xs = sequence (map f xs)
259 #endif /* __HUGS__ */
261 #ifdef __GLASGOW_HASKELL__
262 -- ---------------------------------------------------------------------------
268 Support for multiple operating system threads and bound threads as described
269 below is currently only available in the GHC runtime system if you use the
270 /-threaded/ option when linking.
272 Other Haskell systems do not currently support multiple operating system threads.
274 A bound thread is a haskell thread that is /bound/ to an operating system
275 thread. While the bound thread is still scheduled by the Haskell run-time
276 system, the operating system thread takes care of all the foreign calls made
279 To a foreign library, the bound thread will look exactly like an ordinary
280 operating system thread created using OS functions like @pthread_create@
283 Bound threads can be created using the 'forkOS' function below. All foreign
284 exported functions are run in a bound thread (bound to the OS thread that
285 called the function). Also, the @main@ action of every Haskell program is
286 run in a bound thread.
288 Why do we need this? Because if a foreign library is called from a thread
289 created using 'forkIO', it won't have access to any /thread-local state/ -
290 state variables that have specific values for each OS thread
291 (see POSIX's @pthread_key_create@ or Win32's @TlsAlloc@). Therefore, some
292 libraries (OpenGL, for example) will not work from a thread created using
293 'forkIO'. They work fine in threads created using 'forkOS' or when called
294 from @main@ or from a @foreign export@.
297 -- | 'True' if bound threads are supported.
298 -- If @rtsSupportsBoundThreads@ is 'False', 'isCurrentThreadBound'
299 -- will always return 'False' and both 'forkOS' and 'runInBoundThread' will
301 foreign import ccall rtsSupportsBoundThreads :: Bool
305 Like 'forkIO', this sparks off a new thread to run the 'IO' computation passed as the
306 first argument, and returns the 'ThreadId' of the newly created
309 However, @forkOS@ uses operating system-supplied multithreading support to create
310 a new operating system thread. The new thread is /bound/, which means that
311 all foreign calls made by the 'IO' computation are guaranteed to be executed
312 in this new operating system thread; also, the operating system thread is not
313 used for any other foreign calls.
315 This means that you can use all kinds of foreign libraries from this thread
316 (even those that rely on thread-local state), without the limitations of 'forkIO'.
318 Just to clarify, 'forkOS' is /only/ necessary if you need to associate
319 a Haskell thread with a particular OS thread. It is not necessary if
320 you only need to make non-blocking foreign calls (see
321 "Control.Concurrent#osthreads"). Neither is it necessary if you want
322 to run threads in parallel on a multiprocessor: threads created with
323 'forkIO' will be shared out amongst the running CPUs (using GHC,
324 @-threaded@, and the @+RTS -N@ runtime option).
327 forkOS :: IO () -> IO ThreadId
329 foreign export ccall forkOS_entry
330 :: StablePtr (IO ()) -> IO ()
332 foreign import ccall "forkOS_entry" forkOS_entry_reimported
333 :: StablePtr (IO ()) -> IO ()
335 forkOS_entry stableAction = do
336 action <- deRefStablePtr stableAction
339 foreign import ccall forkOS_createThread
340 :: StablePtr (IO ()) -> IO CInt
342 failNonThreaded = fail $ "RTS doesn't support multiple OS threads "
343 ++"(use ghc -threaded when linking)"
346 | rtsSupportsBoundThreads = do
348 let action_plus = Exception.catch action childHandler
349 entry <- newStablePtr (myThreadId >>= putMVar mv >> action_plus)
350 err <- forkOS_createThread entry
351 when (err /= 0) $ fail "Cannot create OS thread."
355 | otherwise = failNonThreaded
357 -- | Returns 'True' if the calling thread is /bound/, that is, if it is
358 -- safe to use foreign libraries that rely on thread-local state from the
360 isCurrentThreadBound :: IO Bool
361 isCurrentThreadBound = IO $ \ s# ->
362 case isCurrentThreadBound# s# of
363 (# s2#, flg #) -> (# s2#, not (flg ==# 0#) #)
367 Run the 'IO' computation passed as the first argument. If the calling thread
368 is not /bound/, a bound thread is created temporarily. @runInBoundThread@
369 doesn't finish until the 'IO' computation finishes.
371 You can wrap a series of foreign function calls that rely on thread-local state
372 with @runInBoundThread@ so that you can use them without knowing whether the
373 current thread is /bound/.
375 runInBoundThread :: IO a -> IO a
377 runInBoundThread action
378 | rtsSupportsBoundThreads = do
379 bound <- isCurrentThreadBound
383 ref <- newIORef undefined
384 let action_plus = Exception.try action >>= writeIORef ref
386 bracket (newStablePtr action_plus)
388 (\cEntry -> forkOS_entry_reimported cEntry >> readIORef ref)
389 case resultOrException of
390 Left exception -> Exception.throw exception
391 Right result -> return result
392 | otherwise = failNonThreaded
395 Run the 'IO' computation passed as the first argument. If the calling thread
396 is /bound/, an unbound thread is created temporarily using 'forkIO'.
397 @runInBoundThread@ doesn't finish until the 'IO' computation finishes.
399 Use this function /only/ in the rare case that you have actually observed a
400 performance loss due to the use of bound threads. A program that
401 doesn't need it's main thread to be bound and makes /heavy/ use of concurrency
402 (e.g. a web server), might want to wrap it's @main@ action in
403 @runInUnboundThread@.
405 runInUnboundThread :: IO a -> IO a
407 runInUnboundThread action = do
408 bound <- isCurrentThreadBound
412 forkIO (Exception.try action >>= putMVar mv)
413 takeMVar mv >>= \either -> case either of
414 Left exception -> Exception.throw exception
415 Right result -> return result
418 #endif /* __GLASGOW_HASKELL__ */
420 -- ---------------------------------------------------------------------------
421 -- threadWaitRead/threadWaitWrite
423 -- | Block the current thread until data is available to read on the
424 -- given file descriptor (GHC only).
425 threadWaitRead :: Fd -> IO ()
427 #ifdef mingw32_HOST_OS
428 -- we have no IO manager implementing threadWaitRead on Windows.
429 -- fdReady does the right thing, but we have to call it in a
430 -- separate thread, otherwise threadWaitRead won't be interruptible,
431 -- and this only works with -threaded.
432 | threaded = withThread (waitFd fd 0)
433 | otherwise = case fd of
434 0 -> do hWaitForInput stdin (-1); return ()
435 -- hWaitForInput does work properly, but we can only
436 -- do this for stdin since we know its FD.
437 _ -> error "threadWaitRead requires -threaded on Windows, or use System.IO.hWaitForInput"
439 = GHC.Conc.threadWaitRead fd
442 -- | Block the current thread until data can be written to the
443 -- given file descriptor (GHC only).
444 threadWaitWrite :: Fd -> IO ()
446 #ifdef mingw32_HOST_OS
447 | threaded = withThread (waitFd fd 1)
448 | otherwise = error "threadWaitWrite requires -threaded on Windows"
450 = GHC.Conc.threadWaitWrite fd
453 #ifdef mingw32_HOST_OS
454 foreign import ccall unsafe "rtsSupportsBoundThreads" threaded :: Bool
456 withThread :: IO a -> IO a
459 forkIO $ try io >>= putMVar m
465 waitFd :: Fd -> CInt -> IO ()
467 throwErrnoIfMinus1 "fdReady" $
468 fdReady (fromIntegral fd) write (fromIntegral iNFINITE) 0
471 iNFINITE = 0xFFFFFFFF :: CInt -- urgh
473 foreign import ccall safe "fdReady"
474 fdReady :: CInt -> CInt -> CInt -> CInt -> IO CInt
477 -- ---------------------------------------------------------------------------
482 #osthreads# In GHC, threads created by 'forkIO' are lightweight threads, and
483 are managed entirely by the GHC runtime. Typically Haskell
484 threads are an order of magnitude or two more efficient (in
485 terms of both time and space) than operating system threads.
487 The downside of having lightweight threads is that only one can
488 run at a time, so if one thread blocks in a foreign call, for
489 example, the other threads cannot continue. The GHC runtime
490 works around this by making use of full OS threads where
491 necessary. When the program is built with the @-threaded@
492 option (to link against the multithreaded version of the
493 runtime), a thread making a @safe@ foreign call will not block
494 the other threads in the system; another OS thread will take
495 over running Haskell threads until the original call returns.
496 The runtime maintains a pool of these /worker/ threads so that
497 multiple Haskell threads can be involved in external calls
500 The "System.IO" library manages multiplexing in its own way. On
501 Windows systems it uses @safe@ foreign calls to ensure that
502 threads doing I\/O operations don't block the whole runtime,
503 whereas on Unix systems all the currently blocked I\/O reqwests
504 are managed by a single thread (the /IO manager thread/) using
507 The runtime will run a Haskell thread using any of the available
508 worker OS threads. If you need control over which particular OS
509 thread is used to run a given Haskell thread, perhaps because
510 you need to call a foreign library that uses OS-thread-local
511 state, then you need bound threads (see "Control.Concurrent#boundthreads").
513 If you don't use the @-threaded@ option, then the runtime does
514 not make use of multiple OS threads. Foreign calls will block
515 all other running Haskell threads until the call returns. The
516 "System.IO" library still does multiplexing, so there can be multiple
517 threads doing I\/O, and this is handled internally by the runtime using
523 In a standalone GHC program, only the main thread is
524 required to terminate in order for the process to terminate.
525 Thus all other forked threads will simply terminate at the same
526 time as the main thread (the terminology for this kind of
527 behaviour is \"daemonic threads\").
529 If you want the program to wait for child threads to
530 finish before exiting, you need to program this yourself. A
531 simple mechanism is to have each child thread write to an
532 'MVar' when it completes, and have the main
533 thread wait on all the 'MVar's before
536 > myForkIO :: IO () -> IO (MVar ())
538 > mvar <- newEmptyMVar
539 > forkIO (io `finally` putMVar mvar ())
542 Note that we use 'finally' from the
543 "Control.Exception" module to make sure that the
544 'MVar' is written to even if the thread dies or
545 is killed for some reason.
547 A better method is to keep a global list of all child
548 threads which we should wait for at the end of the program:
550 > children :: MVar [MVar ()]
551 > children = unsafePerformIO (newMVar [])
553 > waitForChildren :: IO ()
554 > waitForChildren = do
555 > cs <- takeMVar children
559 > putMVar children ms
563 > forkChild :: IO () -> IO ThreadId
565 > mvar <- newEmptyMVar
566 > childs <- takeMVar children
567 > putMVar children (mvar:childs)
568 > forkIO (io `finally` putMVar mvar ())
571 > later waitForChildren $
574 The main thread principle also applies to calls to Haskell from
575 outside, using @foreign export@. When the @foreign export@ed
576 function is invoked, it starts a new main thread, and it returns
577 when this main thread terminates. If the call causes new
578 threads to be forked, they may remain in the system after the
579 @foreign export@ed function has returned.
584 GHC implements pre-emptive multitasking: the execution of
585 threads are interleaved in a random fashion. More specifically,
586 a thread may be pre-empted whenever it allocates some memory,
587 which unfortunately means that tight loops which do no
588 allocation tend to lock out other threads (this only seems to
589 happen with pathological benchmark-style code, however).
591 The rescheduling timer runs on a 20ms granularity by
592 default, but this may be altered using the
593 @-i\<n\>@ RTS option. After a rescheduling
594 \"tick\" the running thread is pre-empted as soon as
598 @aaaa@ @bbbb@ example may not
599 work too well on GHC (see Scheduling, above), due
600 to the locking on a 'System.IO.Handle'. Only one thread
601 may hold the lock on a 'System.IO.Handle' at any one
602 time, so if a reschedule happens while a thread is holding the
603 lock, the other thread won't be able to run. The upshot is that
604 the switch from @aaaa@ to
605 @bbbbb@ happens infrequently. It can be
606 improved by lowering the reschedule tick period. We also have a
607 patch that causes a reschedule whenever a thread waiting on a
608 lock is woken up, but haven't found it to be useful for anything
609 other than this example :-)