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
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 -- * GHC's implementation of concurrency
67 -- |This section describes features specific to GHC's
68 -- implementation of Concurrent Haskell.
70 -- ** Terminating the program
82 import Control.Exception as Exception
84 #ifdef __GLASGOW_HASKELL__
86 import GHC.TopHandler ( reportStackOverflow, reportError )
87 import GHC.IOBase ( IO(..) )
88 import GHC.IOBase ( unsafeInterleaveIO )
96 import Control.Concurrent.MVar
97 import Control.Concurrent.Chan
98 import Control.Concurrent.QSem
99 import Control.Concurrent.QSemN
100 import Control.Concurrent.SampleVar
104 The concurrency extension for Haskell is described in the paper
106 <http://www.haskell.org/ghc/docs/papers/concurrent-haskell.ps.gz>.
108 Concurrency is \"lightweight\", which means that both thread creation
109 and context switching overheads are extremely low. Scheduling of
110 Haskell threads is done internally in the Haskell runtime system, and
111 doesn't make use of any operating system-supplied thread packages.
113 Haskell threads can communicate via 'MVar's, a kind of synchronised
114 mutable variable (see "Control.Concurrent.MVar"). Several common
115 concurrency abstractions can be built from 'MVar's, and these are
116 provided by the "Concurrent" library. Threads may also communicate
122 Scheduling may be either pre-emptive or co-operative,
123 depending on the implementation of Concurrent Haskell (see below
124 for imformation related to specific compilers). In a co-operative
125 system, context switches only occur when you use one of the
126 primitives defined in this module. This means that programs such
130 > main = forkIO (write 'a') >> write 'b'
131 > where write c = putChar c >> write c
133 will print either @aaaaaaaaaaaaaa...@ or @bbbbbbbbbbbb...@,
134 instead of some random interleaving of @a@s and @b@s. In
135 practice, cooperative multitasking is sufficient for writing
136 simple graphical user interfaces.
140 Calling a foreign C procedure (such as @getchar@) that blocks waiting
141 for input will block /all/ threads, unless the @threadsafe@ attribute
142 is used on the foreign call (and your compiler \/ operating system
143 supports it). GHC's I\/O system uses non-blocking I\/O internally to
144 implement thread-friendly I\/O, so calling standard Haskell I\/O
145 functions blocks only the thread making the call.
148 -- Thread Ids, specifically the instances of Eq and Ord for these things.
149 -- The ThreadId type itself is defined in std/PrelConc.lhs.
151 -- Rather than define a new primitve, we use a little helper function
152 -- cmp_thread in the RTS.
154 #ifdef __GLASGOW_HASKELL__
155 id2TSO :: ThreadId -> ThreadId#
156 id2TSO (ThreadId t) = t
158 foreign import ccall unsafe "cmp_thread" cmp_thread :: ThreadId# -> ThreadId# -> Int
161 cmpThread :: ThreadId -> ThreadId -> Ordering
163 case cmp_thread (id2TSO t1) (id2TSO t2) of
168 instance Eq ThreadId where
170 case t1 `cmpThread` t2 of
174 instance Ord ThreadId where
177 foreign import ccall unsafe "rts_getThreadId" getThreadId :: ThreadId# -> Int
179 instance Show ThreadId where
181 showString "ThreadId " .
182 showsPrec d (getThreadId (id2TSO t))
185 This sparks off a new thread to run the 'IO' computation passed as the
186 first argument, and returns the 'ThreadId' of the newly created
189 forkIO :: IO () -> IO ThreadId
190 forkIO action = IO $ \ s ->
191 case (fork# action_plus s) of (# s1, id #) -> (# s1, ThreadId id #)
193 action_plus = Exception.catch action childHandler
195 childHandler :: Exception -> IO ()
196 childHandler err = Exception.catch (real_handler err) childHandler
198 real_handler :: Exception -> IO ()
201 -- ignore thread GC and killThread exceptions:
202 BlockedOnDeadMVar -> return ()
203 AsyncException ThreadKilled -> return ()
205 -- report all others:
206 AsyncException StackOverflow -> reportStackOverflow False
207 ErrorCall s -> reportError False s
208 other -> reportError False (showsPrec 0 other "\n")
210 #endif /* __GLASGOW_HASKELL__ */
216 mergeIO :: [a] -> [a] -> IO [a]
217 nmergeIO :: [[a]] -> IO [a]
220 -- The 'mergeIO' and 'nmergeIO' functions fork one thread for each
221 -- input list that concurrently evaluates that list; the results are
222 -- merged into a single output list.
224 -- Note: Hugs does not provide these functions, since they require
225 -- preemptive multitasking.
228 = newEmptyMVar >>= \ tail_node ->
229 newMVar tail_node >>= \ tail_list ->
230 newQSem max_buff_size >>= \ e ->
231 newMVar 2 >>= \ branches_running ->
235 forkIO (suckIO branches_running buff ls) >>
236 forkIO (suckIO branches_running buff rs) >>
237 takeMVar tail_node >>= \ val ->
242 = (MVar (MVar [a]), QSem)
244 suckIO :: MVar Int -> Buffer a -> [a] -> IO ()
246 suckIO branches_running buff@(tail_list,e) vs
248 [] -> takeMVar branches_running >>= \ val ->
250 takeMVar tail_list >>= \ node ->
252 putMVar tail_list node
254 putMVar branches_running (val-1)
257 takeMVar tail_list >>= \ node ->
258 newEmptyMVar >>= \ next_node ->
260 takeMVar next_node >>= \ y ->
262 return y) >>= \ next_node_val ->
263 putMVar node (x:next_node_val) >>
264 putMVar tail_list next_node >>
265 suckIO branches_running buff xs
271 newEmptyMVar >>= \ tail_node ->
272 newMVar tail_node >>= \ tail_list ->
273 newQSem max_buff_size >>= \ e ->
274 newMVar len >>= \ branches_running ->
278 mapIO (\ x -> forkIO (suckIO branches_running buff x)) lss >>
279 takeMVar tail_node >>= \ val ->
283 mapIO f xs = sequence (map f xs)
284 #endif /* __HUGS__ */
286 -- ---------------------------------------------------------------------------
291 In a standalone GHC program, only the main thread is
292 required to terminate in order for the process to terminate.
293 Thus all other forked threads will simply terminate at the same
294 time as the main thread (the terminology for this kind of
295 behaviour is \"daemonic threads\").
297 If you want the program to wait for child threads to
298 finish before exiting, you need to program this yourself. A
299 simple mechanism is to have each child thread write to an
300 'MVar' when it completes, and have the main
301 thread wait on all the 'MVar's before
304 > myForkIO :: IO () -> IO (MVar ())
306 > mvar \<- newEmptyMVar
307 > forkIO (io \`finally\` putMVar mvar ())
310 Note that we use 'finally' from the
311 "Exception" module to make sure that the
312 'MVar' is written to even if the thread dies or
313 is killed for some reason.
315 A better method is to keep a global list of all child
316 threads which we should wait for at the end of the program:
318 > children :: MVar [MVar ()]
319 > children = unsafePerformIO (newMVar [])
321 > waitForChildren :: IO ()
322 > waitForChildren = do
323 > (mvar:mvars) \<- takeMVar children
324 > putMVar children mvars
328 > forkChild :: IO () -> IO ()
330 > mvar \<- newEmptyMVar
331 > forkIO (p \`finally\` putMVar mvar ())
332 > childs \<- takeMVar children
333 > putMVar children (mvar:childs)
335 > later = flip finally
338 > later waitForChildren $
341 The main thread principle also applies to calls to Haskell from
342 outside, using @foreign export@. When the @foreign export@ed
343 function is invoked, it starts a new main thread, and it returns
344 when this main thread terminates. If the call causes new
345 threads to be forked, they may remain in the system after the
346 @foreign export@ed function has returned.
351 GHC implements pre-emptive multitasking: the execution of
352 threads are interleaved in a random fashion. More specifically,
353 a thread may be pre-empted whenever it allocates some memory,
354 which unfortunately means that tight loops which do no
355 allocation tend to lock out other threads (this only seems to
356 happen with pathalogical benchmark-style code, however).
358 The rescheduling timer runs on a 20ms granularity by
359 default, but this may be altered using the
360 @-i<n>@ RTS option. After a rescheduling
361 \"tick\" the running thread is pre-empted as soon as
365 @aaaa@ @bbbb@ example may not
366 work too well on GHC (see Scheduling, above), due
367 to the locking on a 'Handle'. Only one thread
368 may hold the lock on a 'Handle' at any one
369 time, so if a reschedule happens while a thread is holding the
370 lock, the other thread won't be able to run. The upshot is that
371 the switch from @aaaa@ to
372 @bbbbb@ happens infrequently. It can be
373 improved by lowering the reschedule tick period. We also have a
374 patch that causes a reschedule whenever a thread waiting on a
375 lock is woken up, but haven't found it to be useful for anything
376 other than this example :-)