2 , ForeignFunctionInterface
7 {-# OPTIONS_GHC -fno-warn-unused-imports #-}
9 -----------------------------------------------------------------------------
11 -- Module : Control.Concurrent
12 -- Copyright : (c) The University of Glasgow 2001
13 -- License : BSD-style (see the file libraries/base/LICENSE)
15 -- Maintainer : libraries@haskell.org
16 -- Stability : experimental
17 -- Portability : non-portable (concurrency)
19 -- A common interface to a collection of useful concurrency
22 -----------------------------------------------------------------------------
24 module Control.Concurrent (
25 -- * Concurrent Haskell
29 -- * Basic concurrency operations
32 #ifdef __GLASGOW_HASKELL__
37 #ifdef __GLASGOW_HASKELL__
52 #ifdef __GLASGOW_HASKELL__
54 threadDelay, -- :: Int -> IO ()
55 threadWaitRead, -- :: Int -> IO ()
56 threadWaitWrite, -- :: Int -> IO ()
59 -- * Communication abstractions
61 module Control.Concurrent.MVar,
62 module Control.Concurrent.Chan,
63 module Control.Concurrent.QSem,
64 module Control.Concurrent.QSemN,
65 module Control.Concurrent.SampleVar,
67 -- * Merging of streams
69 mergeIO, -- :: [a] -> [a] -> IO [a]
70 nmergeIO, -- :: [[a]] -> IO [a]
74 #ifdef __GLASGOW_HASKELL__
77 rtsSupportsBoundThreads,
84 -- * GHC's implementation of concurrency
86 -- |This section describes features specific to GHC's
87 -- implementation of Concurrent Haskell.
89 -- ** Haskell threads and Operating System threads
93 -- ** Terminating the program
101 -- * Deprecated functions
108 import Control.Exception.Base as Exception
110 #ifdef __GLASGOW_HASKELL__
112 import GHC.Conc hiding (threadWaitRead, threadWaitWrite)
113 import qualified GHC.Conc
114 import GHC.IO ( IO(..), unsafeInterleaveIO, unsafeUnmask )
115 import GHC.IORef ( newIORef, readIORef, writeIORef )
118 import System.Posix.Types ( Fd )
119 import Foreign.StablePtr
120 import Foreign.C.Types ( CInt )
121 import Control.Monad ( when )
123 #ifdef mingw32_HOST_OS
133 import Control.Concurrent.MVar
134 import Control.Concurrent.Chan
135 import Control.Concurrent.QSem
136 import Control.Concurrent.QSemN
137 import Control.Concurrent.SampleVar
145 The concurrency extension for Haskell is described in the paper
147 <http://www.haskell.org/ghc/docs/papers/concurrent-haskell.ps.gz>.
149 Concurrency is \"lightweight\", which means that both thread creation
150 and context switching overheads are extremely low. Scheduling of
151 Haskell threads is done internally in the Haskell runtime system, and
152 doesn't make use of any operating system-supplied thread packages.
154 However, if you want to interact with a foreign library that expects your
155 program to use the operating system-supplied thread package, you can do so
156 by using 'forkOS' instead of 'forkIO'.
158 Haskell threads can communicate via 'MVar's, a kind of synchronised
159 mutable variable (see "Control.Concurrent.MVar"). Several common
160 concurrency abstractions can be built from 'MVar's, and these are
161 provided by the "Control.Concurrent" library.
162 In GHC, threads may also communicate via exceptions.
167 Scheduling may be either pre-emptive or co-operative,
168 depending on the implementation of Concurrent Haskell (see below
169 for information related to specific compilers). In a co-operative
170 system, context switches only occur when you use one of the
171 primitives defined in this module. This means that programs such
175 > main = forkIO (write 'a') >> write 'b'
176 > where write c = putChar c >> write c
178 will print either @aaaaaaaaaaaaaa...@ or @bbbbbbbbbbbb...@,
179 instead of some random interleaving of @a@s and @b@s. In
180 practice, cooperative multitasking is sufficient for writing
181 simple graphical user interfaces.
185 Different Haskell implementations have different characteristics with
186 regard to which operations block /all/ threads.
188 Using GHC without the @-threaded@ option, all foreign calls will block
189 all other Haskell threads in the system, although I\/O operations will
190 not. With the @-threaded@ option, only foreign calls with the @unsafe@
191 attribute will block all other threads.
193 Using Hugs, all I\/O operations and foreign calls will block all other
201 mergeIO :: [a] -> [a] -> IO [a]
202 nmergeIO :: [[a]] -> IO [a]
205 -- The 'mergeIO' and 'nmergeIO' functions fork one thread for each
206 -- input list that concurrently evaluates that list; the results are
207 -- merged into a single output list.
209 -- Note: Hugs does not provide these functions, since they require
210 -- preemptive multitasking.
213 = newEmptyMVar >>= \ tail_node ->
214 newMVar tail_node >>= \ tail_list ->
215 newQSem max_buff_size >>= \ e ->
216 newMVar 2 >>= \ branches_running ->
220 forkIO (suckIO branches_running buff ls) >>
221 forkIO (suckIO branches_running buff rs) >>
222 takeMVar tail_node >>= \ val ->
227 = (MVar (MVar [a]), QSem)
229 suckIO :: MVar Int -> Buffer a -> [a] -> IO ()
231 suckIO branches_running buff@(tail_list,e) vs
233 [] -> takeMVar branches_running >>= \ val ->
235 takeMVar tail_list >>= \ node ->
237 putMVar tail_list node
239 putMVar branches_running (val-1)
242 takeMVar tail_list >>= \ node ->
243 newEmptyMVar >>= \ next_node ->
245 takeMVar next_node >>= \ y ->
247 return y) >>= \ next_node_val ->
248 putMVar node (x:next_node_val) >>
249 putMVar tail_list next_node >>
250 suckIO branches_running buff xs
256 newEmptyMVar >>= \ tail_node ->
257 newMVar tail_node >>= \ tail_list ->
258 newQSem max_buff_size >>= \ e ->
259 newMVar len >>= \ branches_running ->
263 mapIO (\ x -> forkIO (suckIO branches_running buff x)) lss >>
264 takeMVar tail_node >>= \ val ->
268 mapIO f xs = sequence (map f xs)
269 #endif /* __HUGS__ */
271 #ifdef __GLASGOW_HASKELL__
272 -- ---------------------------------------------------------------------------
278 Support for multiple operating system threads and bound threads as described
279 below is currently only available in the GHC runtime system if you use the
280 /-threaded/ option when linking.
282 Other Haskell systems do not currently support multiple operating system threads.
284 A bound thread is a haskell thread that is /bound/ to an operating system
285 thread. While the bound thread is still scheduled by the Haskell run-time
286 system, the operating system thread takes care of all the foreign calls made
289 To a foreign library, the bound thread will look exactly like an ordinary
290 operating system thread created using OS functions like @pthread_create@
293 Bound threads can be created using the 'forkOS' function below. All foreign
294 exported functions are run in a bound thread (bound to the OS thread that
295 called the function). Also, the @main@ action of every Haskell program is
296 run in a bound thread.
298 Why do we need this? Because if a foreign library is called from a thread
299 created using 'forkIO', it won't have access to any /thread-local state/ -
300 state variables that have specific values for each OS thread
301 (see POSIX's @pthread_key_create@ or Win32's @TlsAlloc@). Therefore, some
302 libraries (OpenGL, for example) will not work from a thread created using
303 'forkIO'. They work fine in threads created using 'forkOS' or when called
304 from @main@ or from a @foreign export@.
306 In terms of performance, 'forkOS' (aka bound) threads are much more
307 expensive than 'forkIO' (aka unbound) threads, because a 'forkOS'
308 thread is tied to a particular OS thread, whereas a 'forkIO' thread
309 can be run by any OS thread. Context-switching between a 'forkOS'
310 thread and a 'forkIO' thread is many times more expensive than between
311 two 'forkIO' threads.
313 Note in particular that the main program thread (the thread running
314 @Main.main@) is always a bound thread, so for good concurrency
315 performance you should ensure that the main thread is not doing
316 repeated communication with other threads in the system. Typically
317 this means forking subthreads to do the work using 'forkIO', and
318 waiting for the results in the main thread.
322 -- | 'True' if bound threads are supported.
323 -- If @rtsSupportsBoundThreads@ is 'False', 'isCurrentThreadBound'
324 -- will always return 'False' and both 'forkOS' and 'runInBoundThread' will
326 foreign import ccall rtsSupportsBoundThreads :: Bool
330 Like 'forkIO', this sparks off a new thread to run the 'IO'
331 computation passed as the first argument, and returns the 'ThreadId'
332 of the newly created thread.
334 However, 'forkOS' creates a /bound/ thread, which is necessary if you
335 need to call foreign (non-Haskell) libraries that make use of
336 thread-local state, such as OpenGL (see "Control.Concurrent#boundthreads").
338 Using 'forkOS' instead of 'forkIO' makes no difference at all to the
339 scheduling behaviour of the Haskell runtime system. It is a common
340 misconception that you need to use 'forkOS' instead of 'forkIO' to
341 avoid blocking all the Haskell threads when making a foreign call;
342 this isn't the case. To allow foreign calls to be made without
343 blocking all the Haskell threads (with GHC), it is only necessary to
344 use the @-threaded@ option when linking your program, and to make sure
345 the foreign import is not marked @unsafe@.
348 forkOS :: IO () -> IO ThreadId
350 foreign export ccall forkOS_entry
351 :: StablePtr (IO ()) -> IO ()
353 foreign import ccall "forkOS_entry" forkOS_entry_reimported
354 :: StablePtr (IO ()) -> IO ()
356 forkOS_entry :: StablePtr (IO ()) -> IO ()
357 forkOS_entry stableAction = do
358 action <- deRefStablePtr stableAction
361 foreign import ccall forkOS_createThread
362 :: StablePtr (IO ()) -> IO CInt
364 failNonThreaded :: IO a
365 failNonThreaded = fail $ "RTS doesn't support multiple OS threads "
366 ++"(use ghc -threaded when linking)"
369 | rtsSupportsBoundThreads = do
371 b <- Exception.getMaskingState
373 -- async exceptions are masked in the child if they are masked
374 -- in the parent, as for forkIO (see #1048). forkOS_createThread
375 -- creates a thread with exceptions masked by default.
377 Unmasked -> unsafeUnmask action0
378 MaskedInterruptible -> action0
379 MaskedUninterruptible -> uninterruptibleMask_ action0
381 action_plus = Exception.catch action1 childHandler
383 entry <- newStablePtr (myThreadId >>= putMVar mv >> action_plus)
384 err <- forkOS_createThread entry
385 when (err /= 0) $ fail "Cannot create OS thread."
389 | otherwise = failNonThreaded
391 -- | Returns 'True' if the calling thread is /bound/, that is, if it is
392 -- safe to use foreign libraries that rely on thread-local state from the
394 isCurrentThreadBound :: IO Bool
395 isCurrentThreadBound = IO $ \ s# ->
396 case isCurrentThreadBound# s# of
397 (# s2#, flg #) -> (# s2#, not (flg ==# 0#) #)
401 Run the 'IO' computation passed as the first argument. If the calling thread
402 is not /bound/, a bound thread is created temporarily. @runInBoundThread@
403 doesn't finish until the 'IO' computation finishes.
405 You can wrap a series of foreign function calls that rely on thread-local state
406 with @runInBoundThread@ so that you can use them without knowing whether the
407 current thread is /bound/.
409 runInBoundThread :: IO a -> IO a
411 runInBoundThread action
412 | rtsSupportsBoundThreads = do
413 bound <- isCurrentThreadBound
417 ref <- newIORef undefined
418 let action_plus = Exception.try action >>= writeIORef ref
419 bracket (newStablePtr action_plus)
421 (\cEntry -> forkOS_entry_reimported cEntry >> readIORef ref) >>=
423 | otherwise = failNonThreaded
426 Run the 'IO' computation passed as the first argument. If the calling thread
427 is /bound/, an unbound thread is created temporarily using 'forkIO'.
428 @runInBoundThread@ doesn't finish until the 'IO' computation finishes.
430 Use this function /only/ in the rare case that you have actually observed a
431 performance loss due to the use of bound threads. A program that
432 doesn't need it's main thread to be bound and makes /heavy/ use of concurrency
433 (e.g. a web server), might want to wrap it's @main@ action in
434 @runInUnboundThread@.
436 Note that exceptions which are thrown to the current thread are thrown in turn
437 to the thread that is executing the given computation. This ensures there's
438 always a way of killing the forked thread.
440 runInUnboundThread :: IO a -> IO a
442 runInUnboundThread action = do
443 bound <- isCurrentThreadBound
447 mask $ \restore -> do
448 tid <- forkIO $ Exception.try (restore action) >>= putMVar mv
449 let wait = takeMVar mv `Exception.catch` \(e :: SomeException) ->
450 Exception.throwTo tid e >> wait
451 wait >>= unsafeResult
454 unsafeResult :: Either SomeException a -> IO a
455 unsafeResult = either Exception.throwIO return
456 #endif /* __GLASGOW_HASKELL__ */
458 #ifdef __GLASGOW_HASKELL__
459 -- ---------------------------------------------------------------------------
460 -- threadWaitRead/threadWaitWrite
462 -- | Block the current thread until data is available to read on the
463 -- given file descriptor (GHC only).
465 -- This will throw an 'IOError' if the file descriptor was closed
466 -- while this thread was blocked. To safely close a file descriptor
467 -- that has been used with 'threadWaitRead', use
468 -- 'GHC.Conc.closeFdWith'.
469 threadWaitRead :: Fd -> IO ()
471 #ifdef mingw32_HOST_OS
472 -- we have no IO manager implementing threadWaitRead on Windows.
473 -- fdReady does the right thing, but we have to call it in a
474 -- separate thread, otherwise threadWaitRead won't be interruptible,
475 -- and this only works with -threaded.
476 | threaded = withThread (waitFd fd 0)
477 | otherwise = case fd of
478 0 -> do _ <- hWaitForInput stdin (-1)
480 -- hWaitForInput does work properly, but we can only
481 -- do this for stdin since we know its FD.
482 _ -> error "threadWaitRead requires -threaded on Windows, or use System.IO.hWaitForInput"
484 = GHC.Conc.threadWaitRead fd
487 -- | Block the current thread until data can be written to the
488 -- given file descriptor (GHC only).
490 -- This will throw an 'IOError' if the file descriptor was closed
491 -- while this thread was blocked. To safely close a file descriptor
492 -- that has been used with 'threadWaitWrite', use
493 -- 'GHC.Conc.closeFdWith'.
494 threadWaitWrite :: Fd -> IO ()
496 #ifdef mingw32_HOST_OS
497 | threaded = withThread (waitFd fd 1)
498 | otherwise = error "threadWaitWrite requires -threaded on Windows"
500 = GHC.Conc.threadWaitWrite fd
503 #ifdef mingw32_HOST_OS
504 foreign import ccall unsafe "rtsSupportsBoundThreads" threaded :: Bool
506 withThread :: IO a -> IO a
509 _ <- mask_ $ forkIO $ try io >>= putMVar m
513 Left e -> throwIO (e :: IOException)
515 waitFd :: Fd -> CInt -> IO ()
517 throwErrnoIfMinus1_ "fdReady" $
518 fdReady (fromIntegral fd) write iNFINITE 0
521 iNFINITE = 0xFFFFFFFF -- urgh
523 foreign import ccall safe "fdReady"
524 fdReady :: CInt -> CInt -> CInt -> CInt -> IO CInt
527 -- ---------------------------------------------------------------------------
532 #osthreads# In GHC, threads created by 'forkIO' are lightweight threads, and
533 are managed entirely by the GHC runtime. Typically Haskell
534 threads are an order of magnitude or two more efficient (in
535 terms of both time and space) than operating system threads.
537 The downside of having lightweight threads is that only one can
538 run at a time, so if one thread blocks in a foreign call, for
539 example, the other threads cannot continue. The GHC runtime
540 works around this by making use of full OS threads where
541 necessary. When the program is built with the @-threaded@
542 option (to link against the multithreaded version of the
543 runtime), a thread making a @safe@ foreign call will not block
544 the other threads in the system; another OS thread will take
545 over running Haskell threads until the original call returns.
546 The runtime maintains a pool of these /worker/ threads so that
547 multiple Haskell threads can be involved in external calls
550 The "System.IO" library manages multiplexing in its own way. On
551 Windows systems it uses @safe@ foreign calls to ensure that
552 threads doing I\/O operations don't block the whole runtime,
553 whereas on Unix systems all the currently blocked I\/O requests
554 are managed by a single thread (the /IO manager thread/) using
557 The runtime will run a Haskell thread using any of the available
558 worker OS threads. If you need control over which particular OS
559 thread is used to run a given Haskell thread, perhaps because
560 you need to call a foreign library that uses OS-thread-local
561 state, then you need bound threads (see "Control.Concurrent#boundthreads").
563 If you don't use the @-threaded@ option, then the runtime does
564 not make use of multiple OS threads. Foreign calls will block
565 all other running Haskell threads until the call returns. The
566 "System.IO" library still does multiplexing, so there can be multiple
567 threads doing I\/O, and this is handled internally by the runtime using
573 In a standalone GHC program, only the main thread is
574 required to terminate in order for the process to terminate.
575 Thus all other forked threads will simply terminate at the same
576 time as the main thread (the terminology for this kind of
577 behaviour is \"daemonic threads\").
579 If you want the program to wait for child threads to
580 finish before exiting, you need to program this yourself. A
581 simple mechanism is to have each child thread write to an
582 'MVar' when it completes, and have the main
583 thread wait on all the 'MVar's before
586 > myForkIO :: IO () -> IO (MVar ())
588 > mvar <- newEmptyMVar
589 > forkIO (io `finally` putMVar mvar ())
592 Note that we use 'finally' from the
593 "Control.Exception" module to make sure that the
594 'MVar' is written to even if the thread dies or
595 is killed for some reason.
597 A better method is to keep a global list of all child
598 threads which we should wait for at the end of the program:
600 > children :: MVar [MVar ()]
601 > children = unsafePerformIO (newMVar [])
603 > waitForChildren :: IO ()
604 > waitForChildren = do
605 > cs <- takeMVar children
609 > putMVar children ms
613 > forkChild :: IO () -> IO ThreadId
615 > mvar <- newEmptyMVar
616 > childs <- takeMVar children
617 > putMVar children (mvar:childs)
618 > forkIO (io `finally` putMVar mvar ())
621 > later waitForChildren $
624 The main thread principle also applies to calls to Haskell from
625 outside, using @foreign export@. When the @foreign export@ed
626 function is invoked, it starts a new main thread, and it returns
627 when this main thread terminates. If the call causes new
628 threads to be forked, they may remain in the system after the
629 @foreign export@ed function has returned.
634 GHC implements pre-emptive multitasking: the execution of
635 threads are interleaved in a random fashion. More specifically,
636 a thread may be pre-empted whenever it allocates some memory,
637 which unfortunately means that tight loops which do no
638 allocation tend to lock out other threads (this only seems to
639 happen with pathological benchmark-style code, however).
641 The rescheduling timer runs on a 20ms granularity by
642 default, but this may be altered using the
643 @-i\<n\>@ RTS option. After a rescheduling
644 \"tick\" the running thread is pre-empted as soon as
648 @aaaa@ @bbbb@ example may not
649 work too well on GHC (see Scheduling, above), due
650 to the locking on a 'System.IO.Handle'. Only one thread
651 may hold the lock on a 'System.IO.Handle' at any one
652 time, so if a reschedule happens while a thread is holding the
653 lock, the other thread won't be able to run. The upshot is that
654 the switch from @aaaa@ to
655 @bbbbb@ happens infrequently. It can be
656 improved by lowering the reschedule tick period. We also have a
657 patch that causes a reschedule whenever a thread waiting on a
658 lock is woken up, but haven't found it to be useful for anything
659 other than this example :-)
661 #endif /* __GLASGOW_HASKELL__ */