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
39 #ifdef __GLASGOW_HASKELL__
41 threadDelay, -- :: Int -> IO ()
42 threadWaitRead, -- :: Int -> IO ()
43 threadWaitWrite, -- :: Int -> IO ()
46 -- * Communication abstractions
48 module Control.Concurrent.MVar,
49 module Control.Concurrent.Chan,
50 module Control.Concurrent.QSem,
51 module Control.Concurrent.QSemN,
52 module Control.Concurrent.SampleVar,
54 -- * Merging of streams
55 mergeIO, -- :: [a] -> [a] -> IO [a]
56 nmergeIO, -- :: [[a]] -> IO [a]
59 -- * GHC's implementation of concurrency
61 -- |This section describes features specific to GHC's
62 -- implementation of Concurrent Haskell.
64 -- ** Terminating the program
76 import Control.Exception as Exception
78 #ifdef __GLASGOW_HASKELL__
80 import GHC.TopHandler ( reportStackOverflow, reportError )
81 import GHC.IOBase ( IO(..) )
82 import GHC.IOBase ( unsafeInterleaveIO )
87 import IOExts ( unsafeInterleaveIO )
91 import Control.Concurrent.MVar
92 import Control.Concurrent.Chan
93 import Control.Concurrent.QSem
94 import Control.Concurrent.QSemN
95 import Control.Concurrent.SampleVar
99 The concurrency extension for Haskell is described in the paper
101 <http://www.haskell.org/ghc/docs/papers/concurrent-haskell.ps.gz>.
103 Concurrency is \"lightweight\", which means that both thread creation
104 and context switching overheads are extremely low. Scheduling of
105 Haskell threads is done internally in the Haskell runtime system, and
106 doesn't make use of any operating system-supplied thread packages.
108 Haskell threads can communicate via 'MVar's, a kind of synchronised
109 mutable variable (see "Control.Concurrent.MVar"). Several common
110 concurrency abstractions can be built from 'MVar's, and these are
111 provided by the "Concurrent" library. Threads may also communicate
117 Scheduling may be either pre-emptive or co-operative,
118 depending on the implementation of Concurrent Haskell (see below
119 for imformation related to specific compilers). In a co-operative
120 system, context switches only occur when you use one of the
121 primitives defined in this module. This means that programs such
125 > main = forkIO (write 'a') >> write 'b'
126 > where write c = putChar c >> write c
128 will print either @aaaaaaaaaaaaaa...@ or @bbbbbbbbbbbb...@,
129 instead of some random interleaving of @a@s and @b@s. In
130 practice, cooperative multitasking is sufficient for writing
131 simple graphical user interfaces.
135 Calling a foreign C procedure (such as @getchar@) that blocks waiting
136 for input will block /all/ threads, unless the @threadsafe@ attribute
137 is used on the foreign call (and your compiler \/ operating system
138 supports it). GHC's I\/O system uses non-blocking I\/O internally to
139 implement thread-friendly I\/O, so calling standard Haskell I\/O
140 functions blocks only the thread making the call.
143 -- Thread Ids, specifically the instances of Eq and Ord for these things.
144 -- The ThreadId type itself is defined in std/PrelConc.lhs.
146 -- Rather than define a new primitve, we use a little helper function
147 -- cmp_thread in the RTS.
149 #ifdef __GLASGOW_HASKELL__
150 id2TSO :: ThreadId -> ThreadId#
151 id2TSO (ThreadId t) = t
153 foreign import ccall unsafe "cmp_thread" cmp_thread :: ThreadId# -> ThreadId# -> Int
156 cmpThread :: ThreadId -> ThreadId -> Ordering
158 case cmp_thread (id2TSO t1) (id2TSO t2) of
163 instance Eq ThreadId where
165 case t1 `cmpThread` t2 of
169 instance Ord ThreadId where
172 foreign import ccall unsafe "rts_getThreadId" getThreadId :: ThreadId# -> Int
174 instance Show ThreadId where
176 showString "ThreadId " .
177 showsPrec d (getThreadId (id2TSO t))
180 This sparks off a new thread to run the 'IO' computation passed as the
181 first argument, and returns the 'ThreadId' of the newly created
184 forkIO :: IO () -> IO ThreadId
185 forkIO action = IO $ \ s ->
186 case (fork# action_plus s) of (# s1, id #) -> (# s1, ThreadId id #)
188 action_plus = Exception.catch action childHandler
190 childHandler :: Exception -> IO ()
191 childHandler err = Exception.catch (real_handler err) childHandler
193 real_handler :: Exception -> IO ()
196 -- ignore thread GC and killThread exceptions:
197 BlockedOnDeadMVar -> return ()
198 AsyncException ThreadKilled -> return ()
200 -- report all others:
201 AsyncException StackOverflow -> reportStackOverflow False
202 ErrorCall s -> reportError False s
203 other -> reportError False (showsPrec 0 other "\n")
205 #endif /* __GLASGOW_HASKELL__ */
211 mergeIO :: [a] -> [a] -> IO [a]
212 nmergeIO :: [[a]] -> IO [a]
215 -- The 'mergeIO' and 'nmergeIO' functions fork one thread for each
216 -- input list that concurrently evaluates that list; the results are
217 -- merged into a single output list.
219 -- Note: Hugs does not provide these functions, since they require
220 -- preemptive multitasking.
223 = newEmptyMVar >>= \ tail_node ->
224 newMVar tail_node >>= \ tail_list ->
225 newQSem max_buff_size >>= \ e ->
226 newMVar 2 >>= \ branches_running ->
230 forkIO (suckIO branches_running buff ls) >>
231 forkIO (suckIO branches_running buff rs) >>
232 takeMVar tail_node >>= \ val ->
237 = (MVar (MVar [a]), QSem)
239 suckIO :: MVar Int -> Buffer a -> [a] -> IO ()
241 suckIO branches_running buff@(tail_list,e) vs
243 [] -> takeMVar branches_running >>= \ val ->
245 takeMVar tail_list >>= \ node ->
247 putMVar tail_list node
249 putMVar branches_running (val-1)
252 takeMVar tail_list >>= \ node ->
253 newEmptyMVar >>= \ next_node ->
255 takeMVar next_node >>= \ y ->
257 return y) >>= \ next_node_val ->
258 putMVar node (x:next_node_val) >>
259 putMVar tail_list next_node >>
260 suckIO branches_running buff xs
266 newEmptyMVar >>= \ tail_node ->
267 newMVar tail_node >>= \ tail_list ->
268 newQSem max_buff_size >>= \ e ->
269 newMVar len >>= \ branches_running ->
273 mapIO (\ x -> forkIO (suckIO branches_running buff x)) lss >>
274 takeMVar tail_node >>= \ val ->
278 mapIO f xs = sequence (map f xs)
280 -- ---------------------------------------------------------------------------
285 In a standalone GHC program, only the main thread is
286 required to terminate in order for the process to terminate.
287 Thus all other forked threads will simply terminate at the same
288 time as the main thread (the terminology for this kind of
289 behaviour is \"daemonic threads\").
291 If you want the program to wait for child threads to
292 finish before exiting, you need to program this yourself. A
293 simple mechanism is to have each child thread write to an
294 'MVar' when it completes, and have the main
295 thread wait on all the 'MVar's before
298 > myForkIO :: IO () -> IO (MVar ())
300 > mvar \<- newEmptyMVar
301 > forkIO (io \`finally\` putMVar mvar ())
304 Note that we use 'finally' from the
305 "Exception" module to make sure that the
306 'MVar' is written to even if the thread dies or
307 is killed for some reason.
309 A better method is to keep a global list of all child
310 threads which we should wait for at the end of the program:
312 > children :: MVar [MVar ()]
313 > children = unsafePerformIO (newMVar [])
315 > waitForChildren :: IO ()
316 > waitForChildren = do
317 > (mvar:mvars) \<- takeMVar children
318 > putMVar children mvars
322 > forkChild :: IO () -> IO ()
324 > mvar \<- newEmptyMVar
325 > forkIO (p \`finally\` putMVar mvar ())
326 > childs \<- takeMVar children
327 > putMVar children (mvar:childs)
329 > later = flip finally
332 > later waitForChildren $
335 The main thread principle also applies to calls to Haskell from
336 outside, using @foreign export@. When the @foreign export@ed
337 function is invoked, it starts a new main thread, and it returns
338 when this main thread terminates. If the call causes new
339 threads to be forked, they may remain in the system after the
340 @foreign export@ed function has returned.
345 GHC implements pre-emptive multitasking: the execution of
346 threads are interleaved in a random fashion. More specifically,
347 a thread may be pre-empted whenever it allocates some memory,
348 which unfortunately means that tight loops which do no
349 allocation tend to lock out other threads (this only seems to
350 happen with pathalogical benchmark-style code, however).
352 The rescheduling timer runs on a 20ms granularity by
353 default, but this may be altered using the
354 @-i<n>@ RTS option. After a rescheduling
355 \"tick\" the running thread is pre-empted as soon as
359 @aaaa@ @bbbb@ example may not
360 work too well on GHC (see Scheduling, above), due
361 to the locking on a 'Handle'. Only one thread
362 may hold the lock on a 'Handle' at any one
363 time, so if a reschedule happens while a thread is holding the
364 lock, the other thread won't be able to run. The upshot is that
365 the switch from @aaaa@ to
366 @bbbbb@ happens infrequently. It can be
367 improved by lowering the reschedule tick period. We also have a
368 patch that causes a reschedule whenever a thread waiting on a
369 lock is woken up, but haven't found it to be useful for anything
370 other than this example :-)