<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>Control.Concurrent</title><link href="ocean.css" rel="stylesheet" type="text/css" title="Ocean" /><script src="haddock-util.js" type="text/javascript"></script><script type="text/javascript">//<![CDATA[ window.onload = function () {pageLoad();setSynopsis("mini_Control-Concurrent.html");}; //]]> </script></head><body><div id="package-header"><ul class="links" id="page-menu"><li><a href="index.html">Contents</a></li><li><a href="doc-index.html">Index</a></li></ul><p class="caption">base-4.3.1.0: Basic libraries</p></div><div id="content"><div id="module-header"><table class="info"><tr><th>Portability</th><td>non-portable (concurrency)</td></tr><tr><th>Stability</th><td>experimental</td></tr><tr><th>Maintainer</th><td>libraries@haskell.org</td></tr></table><p class="caption">Control.Concurrent</p></div><div id="table-of-contents"><p class="caption">Contents</p><ul><li><a href="#g:1">Concurrent Haskell </a></li><li><a href="#g:2">Basic concurrency operations </a></li><li><a href="#g:3">Scheduling </a><ul><li><a href="#g:4">Blocking </a></li><li><a href="#g:5">Waiting </a></li></ul></li><li><a href="#g:6">Communication abstractions </a></li><li><a href="#g:7">Merging of streams </a></li><li><a href="#g:8">Bound Threads </a></li><li><a href="#g:9">GHC's implementation of concurrency </a><ul><li><a href="#g:10">Haskell threads and Operating System threads </a></li><li><a href="#g:11">Terminating the program </a></li><li><a href="#g:12">Pre-emption </a></li></ul></li></ul></div><div id="description"><p class="caption">Description</p><div class="doc"><p>A common interface to a collection of useful concurrency abstractions. </p></div></div><div id="synopsis"><p id="control.syn" class="caption expander" onclick="toggleSection('syn')">Synopsis</p><ul id="section.syn" class="hide" onclick="toggleSection('syn')"><li class="src short"><span class="keyword">data</span> <a href="#t:ThreadId">ThreadId</a> </li><li class="src short"><a href="#v:myThreadId">myThreadId</a> :: <a href="System-IO.html#t:IO">IO</a> <a href="Control-Concurrent.html#t:ThreadId">ThreadId</a></li><li class="src short"><a href="#v:forkIO">forkIO</a> :: <a href="System-IO.html#t:IO">IO</a> <a href="../ghc-prim-0.2.0.0/GHC-Unit.html#t:-40--41-">()</a> -> <a href="System-IO.html#t:IO">IO</a> <a href="Control-Concurrent.html#t:ThreadId">ThreadId</a></li><li class="src short"><a href="#v:forkIOUnmasked">forkIOUnmasked</a> :: <a href="System-IO.html#t:IO">IO</a> <a href="../ghc-prim-0.2.0.0/GHC-Unit.html#t:-40--41-">()</a> -> <a href="System-IO.html#t:IO">IO</a> <a href="Control-Concurrent.html#t:ThreadId">ThreadId</a></li><li class="src short"><a href="#v:killThread">killThread</a> :: <a href="Control-Concurrent.html#t:ThreadId">ThreadId</a> -> <a href="System-IO.html#t:IO">IO</a> <a href="../ghc-prim-0.2.0.0/GHC-Unit.html#t:-40--41-">()</a></li><li class="src short"><a href="#v:throwTo">throwTo</a> :: <a href="Control-Exception-Base.html#t:Exception">Exception</a> e => <a href="Control-Concurrent.html#t:ThreadId">ThreadId</a> -> e -> <a href="System-IO.html#t:IO">IO</a> <a href="../ghc-prim-0.2.0.0/GHC-Unit.html#t:-40--41-">()</a></li><li class="src short"><a href="#v:yield">yield</a> :: <a href="System-IO.html#t:IO">IO</a> <a href="../ghc-prim-0.2.0.0/GHC-Unit.html#t:-40--41-">()</a></li><li class="src short"><a href="#v:threadDelay">threadDelay</a> :: <a href="Data-Int.html#t:Int">Int</a> -> <a href="System-IO.html#t:IO">IO</a> <a href="../ghc-prim-0.2.0.0/GHC-Unit.html#t:-40--41-">()</a></li><li class="src short"><a href="#v:threadWaitRead">threadWaitRead</a> :: <a href="System-Posix-Types.html#t:Fd">Fd</a> -> <a href="System-IO.html#t:IO">IO</a> <a href="../ghc-prim-0.2.0.0/GHC-Unit.html#t:-40--41-">()</a></li><li class="src short"><a href="#v:threadWaitWrite">threadWaitWrite</a> :: <a href="System-Posix-Types.html#t:Fd">Fd</a> -> <a href="System-IO.html#t:IO">IO</a> <a href="../ghc-prim-0.2.0.0/GHC-Unit.html#t:-40--41-">()</a></li><li class="src short">module <a href="Control-Concurrent-MVar.html">Control.Concurrent.MVar</a></li><li class="src short">module <a href="Control-Concurrent-Chan.html">Control.Concurrent.Chan</a></li><li class="src short">module <a href="Control-Concurrent-QSem.html">Control.Concurrent.QSem</a></li><li class="src short">module <a href="Control-Concurrent-QSemN.html">Control.Concurrent.QSemN</a></li><li class="src short">module <a href="Control-Concurrent-SampleVar.html">Control.Concurrent.SampleVar</a></li><li class="src short"><a href="#v:mergeIO">mergeIO</a> :: [a] -> [a] -> <a href="System-IO.html#t:IO">IO</a> [a]</li><li class="src short"><a href="#v:nmergeIO">nmergeIO</a> :: [[a]] -> <a href="System-IO.html#t:IO">IO</a> [a]</li><li class="src short"><a href="#v:rtsSupportsBoundThreads">rtsSupportsBoundThreads</a> :: <a href="Data-Bool.html#t:Bool">Bool</a></li><li class="src short"><a href="#v:forkOS">forkOS</a> :: <a href="System-IO.html#t:IO">IO</a> <a href="../ghc-prim-0.2.0.0/GHC-Unit.html#t:-40--41-">()</a> -> <a href="System-IO.html#t:IO">IO</a> <a href="Control-Concurrent.html#t:ThreadId">ThreadId</a></li><li class="src short"><a href="#v:isCurrentThreadBound">isCurrentThreadBound</a> :: <a href="System-IO.html#t:IO">IO</a> <a href="Data-Bool.html#t:Bool">Bool</a></li><li class="src short"><a href="#v:runInBoundThread">runInBoundThread</a> :: <a href="System-IO.html#t:IO">IO</a> a -> <a href="System-IO.html#t:IO">IO</a> a</li><li class="src short"><a href="#v:runInUnboundThread">runInUnboundThread</a> :: <a href="System-IO.html#t:IO">IO</a> a -> <a href="System-IO.html#t:IO">IO</a> a</li></ul></div><div id="interface"><h1 id="g:1">Concurrent Haskell </h1><div class="doc"><p>The concurrency extension for Haskell is described in the paper <em>Concurrent Haskell</em> <a href="http://www.haskell.org/ghc/docs/papers/concurrent-haskell.ps.gz">http://www.haskell.org/ghc/docs/papers/concurrent-haskell.ps.gz</a>. </p><p>Concurrency is "lightweight", which means that both thread creation and context switching overheads are extremely low. Scheduling of Haskell threads is done internally in the Haskell runtime system, and doesn't make use of any operating system-supplied thread packages. </p><p>However, if you want to interact with a foreign library that expects your program to use the operating system-supplied thread package, you can do so by using <code><a href="Control-Concurrent.html#v:forkOS">forkOS</a></code> instead of <code><a href="Control-Concurrent.html#v:forkIO">forkIO</a></code>. </p><p>Haskell threads can communicate via <code><a href="Control-Concurrent-MVar.html#t:MVar">MVar</a></code>s, a kind of synchronised mutable variable (see <a href="Control-Concurrent-MVar.html">Control.Concurrent.MVar</a>). Several common concurrency abstractions can be built from <code><a href="Control-Concurrent-MVar.html#t:MVar">MVar</a></code>s, and these are provided by the <a href="Control-Concurrent.html">Control.Concurrent</a> library. In GHC, threads may also communicate via exceptions. </p></div><h1 id="g:2">Basic concurrency operations </h1><div class="top"><p class="src"><span class="keyword">data</span> <a name="t:ThreadId" class="def">ThreadId</a> </p><div class="doc"><p>A <code><a href="Control-Concurrent.html#t:ThreadId">ThreadId</a></code> is an abstract type representing a handle to a thread. <code><a href="Control-Concurrent.html#t:ThreadId">ThreadId</a></code> is an instance of <code><a href="Data-Eq.html#t:Eq">Eq</a></code>, <code><a href="Data-Ord.html#t:Ord">Ord</a></code> and <code><a href="Text-Show.html#t:Show">Show</a></code>, where the <code><a href="Data-Ord.html#t:Ord">Ord</a></code> instance implements an arbitrary total ordering over <code><a href="Control-Concurrent.html#t:ThreadId">ThreadId</a></code>s. The <code><a href="Text-Show.html#t:Show">Show</a></code> instance lets you convert an arbitrary-valued <code><a href="Control-Concurrent.html#t:ThreadId">ThreadId</a></code> to string form; showing a <code><a href="Control-Concurrent.html#t:ThreadId">ThreadId</a></code> value is occasionally useful when debugging or diagnosing the behaviour of a concurrent program. </p><p><em>Note</em>: in GHC, if you have a <code><a href="Control-Concurrent.html#t:ThreadId">ThreadId</a></code>, you essentially have a pointer to the thread itself. This means the thread itself can't be garbage collected until you drop the <code><a href="Control-Concurrent.html#t:ThreadId">ThreadId</a></code>. This misfeature will hopefully be corrected at a later date. </p><p><em>Note</em>: Hugs does not provide any operations on other threads; it defines <code><a href="Control-Concurrent.html#t:ThreadId">ThreadId</a></code> as a synonym for (). </p></div><div class="subs instances"><p id="control.i:ThreadId" class="caption collapser" onclick="toggleSection('i:ThreadId')">Instances</p><div id="section.i:ThreadId" class="show"><table><tr><td class="src"><a href="Data-Eq.html#t:Eq">Eq</a> <a href="Control-Concurrent.html#t:ThreadId">ThreadId</a></td><td class="doc empty"> </td></tr><tr><td class="src"><a href="Data-Ord.html#t:Ord">Ord</a> <a href="Control-Concurrent.html#t:ThreadId">ThreadId</a></td><td class="doc empty"> </td></tr><tr><td class="src"><a href="Text-Show.html#t:Show">Show</a> <a href="Control-Concurrent.html#t:ThreadId">ThreadId</a></td><td class="doc empty"> </td></tr><tr><td class="src"><a href="Data-Typeable.html#t:Typeable">Typeable</a> <a href="Control-Concurrent.html#t:ThreadId">ThreadId</a></td><td class="doc empty"> </td></tr></table></div></div></div><div class="top"><p class="src"><a name="v:myThreadId" class="def">myThreadId</a> :: <a href="System-IO.html#t:IO">IO</a> <a href="Control-Concurrent.html#t:ThreadId">ThreadId</a></p><div class="doc"><p>Returns the <code><a href="Control-Concurrent.html#t:ThreadId">ThreadId</a></code> of the calling thread (GHC only). </p></div></div><div class="top"><p class="src"><a name="v:forkIO" class="def">forkIO</a> :: <a href="System-IO.html#t:IO">IO</a> <a href="../ghc-prim-0.2.0.0/GHC-Unit.html#t:-40--41-">()</a> -> <a href="System-IO.html#t:IO">IO</a> <a href="Control-Concurrent.html#t:ThreadId">ThreadId</a></p><div class="doc"><p>Sparks off a new thread to run the <code><a href="System-IO.html#t:IO">IO</a></code> computation passed as the first argument, and returns the <code><a href="Control-Concurrent.html#t:ThreadId">ThreadId</a></code> of the newly created thread. </p><p>The new thread will be a lightweight thread; if you want to use a foreign library that uses thread-local storage, use <code>Control.Concurrent.forkOS</code> instead. </p><p>GHC note: the new thread inherits the <em>masked</em> state of the parent (see <code>Control.Exception.mask</code>). </p><p>The newly created thread has an exception handler that discards the exceptions <code><a href="Control-Exception-Base.html#t:BlockedIndefinitelyOnMVar">BlockedIndefinitelyOnMVar</a></code>, <code><a href="Control-Exception-Base.html#t:BlockedIndefinitelyOnSTM">BlockedIndefinitelyOnSTM</a></code>, and <code><a href="Control-Exception-Base.html#v:ThreadKilled">ThreadKilled</a></code>, and passes all other exceptions to the uncaught exception handler (see <code><a href="GHC-Conc.html#v:setUncaughtExceptionHandler">setUncaughtExceptionHandler</a></code>). </p></div></div><div class="top"><p class="src"><a name="v:forkIOUnmasked" class="def">forkIOUnmasked</a> :: <a href="System-IO.html#t:IO">IO</a> <a href="../ghc-prim-0.2.0.0/GHC-Unit.html#t:-40--41-">()</a> -> <a href="System-IO.html#t:IO">IO</a> <a href="Control-Concurrent.html#t:ThreadId">ThreadId</a></p><div class="doc"><p>Like <code><a href="Control-Concurrent.html#v:forkIO">forkIO</a></code>, but the child thread is created with asynchronous exceptions unmasked (see <code>Control.Exception.mask</code>). </p></div></div><div class="top"><p class="src"><a name="v:killThread" class="def">killThread</a> :: <a href="Control-Concurrent.html#t:ThreadId">ThreadId</a> -> <a href="System-IO.html#t:IO">IO</a> <a href="../ghc-prim-0.2.0.0/GHC-Unit.html#t:-40--41-">()</a></p><div class="doc"><p><code><a href="Control-Concurrent.html#v:killThread">killThread</a></code> raises the <code><a href="Control-Exception-Base.html#v:ThreadKilled">ThreadKilled</a></code> exception in the given thread (GHC only). </p><pre> killThread tid = throwTo tid ThreadKilled </pre></div></div><div class="top"><p class="src"><a name="v:throwTo" class="def">throwTo</a> :: <a href="Control-Exception-Base.html#t:Exception">Exception</a> e => <a href="Control-Concurrent.html#t:ThreadId">ThreadId</a> -> e -> <a href="System-IO.html#t:IO">IO</a> <a href="../ghc-prim-0.2.0.0/GHC-Unit.html#t:-40--41-">()</a></p><div class="doc"><p><code><a href="Control-Concurrent.html#v:throwTo">throwTo</a></code> raises an arbitrary exception in the target thread (GHC only). </p><p><code><a href="Control-Concurrent.html#v:throwTo">throwTo</a></code> does not return until the exception has been raised in the target thread. The calling thread can thus be certain that the target thread has received the exception. This is a useful property to know when dealing with race conditions: eg. if there are two threads that can kill each other, it is guaranteed that only one of the threads will get to kill the other. </p><p>Whatever work the target thread was doing when the exception was raised is not lost: the computation is suspended until required by another thread. </p><p>If the target thread is currently making a foreign call, then the exception will not be raised (and hence <code><a href="Control-Concurrent.html#v:throwTo">throwTo</a></code> will not return) until the call has completed. This is the case regardless of whether the call is inside a <code><a href="Control-Exception-Base.html#v:mask">mask</a></code> or not. </p><p>Important note: the behaviour of <code><a href="Control-Concurrent.html#v:throwTo">throwTo</a></code> differs from that described in the paper "Asynchronous exceptions in Haskell" (<a href="http://research.microsoft.com/~simonpj/Papers/asynch-exns.htm">http://research.microsoft.com/~simonpj/Papers/asynch-exns.htm</a>). In the paper, <code><a href="Control-Concurrent.html#v:throwTo">throwTo</a></code> is non-blocking; but the library implementation adopts a more synchronous design in which <code><a href="Control-Concurrent.html#v:throwTo">throwTo</a></code> does not return until the exception is received by the target thread. The trade-off is discussed in Section 9 of the paper. Like any blocking operation, <code><a href="Control-Concurrent.html#v:throwTo">throwTo</a></code> is therefore interruptible (see Section 5.3 of the paper). Unlike other interruptible operations, however, <code><a href="Control-Concurrent.html#v:throwTo">throwTo</a></code> is <em>always</em> interruptible, even if it does not actually block. </p><p>There is no guarantee that the exception will be delivered promptly, although the runtime will endeavour to ensure that arbitrary delays don't occur. In GHC, an exception can only be raised when a thread reaches a <em>safe point</em>, where a safe point is where memory allocation occurs. Some loops do not perform any memory allocation inside the loop and therefore cannot be interrupted by a <code><a href="Control-Concurrent.html#v:throwTo">throwTo</a></code>. </p><p>Blocked <code><a href="Control-Concurrent.html#v:throwTo">throwTo</a></code> is fair: if multiple threads are trying to throw an exception to the same target thread, they will succeed in FIFO order. </p></div></div><h1 id="g:3">Scheduling </h1><div class="doc"><p>Scheduling may be either pre-emptive or co-operative, depending on the implementation of Concurrent Haskell (see below for information related to specific compilers). In a co-operative system, context switches only occur when you use one of the primitives defined in this module. This means that programs such as: </p><pre> main = forkIO (write 'a') >> write 'b' where write c = putChar c >> write c </pre><p>will print either <code>aaaaaaaaaaaaaa...</code> or <code>bbbbbbbbbbbb...</code>, instead of some random interleaving of <code>a</code>s and <code>b</code>s. In practice, cooperative multitasking is sufficient for writing simple graphical user interfaces. </p></div><div class="top"><p class="src"><a name="v:yield" class="def">yield</a> :: <a href="System-IO.html#t:IO">IO</a> <a href="../ghc-prim-0.2.0.0/GHC-Unit.html#t:-40--41-">()</a></p><div class="doc"><p>The <code><a href="Control-Concurrent.html#v:yield">yield</a></code> action allows (forces, in a co-operative multitasking implementation) a context-switch to any other currently runnable threads (if any), and is occasionally useful when implementing concurrency abstractions. </p></div></div><h2 id="g:4">Blocking </h2><div class="doc"><p>Different Haskell implementations have different characteristics with regard to which operations block <em>all</em> threads. </p><p>Using GHC without the <code>-threaded</code> option, all foreign calls will block all other Haskell threads in the system, although I/O operations will not. With the <code>-threaded</code> option, only foreign calls with the <code>unsafe</code> attribute will block all other threads. </p><p>Using Hugs, all I/O operations and foreign calls will block all other Haskell threads. </p></div><h2 id="g:5">Waiting </h2><div class="top"><p class="src"><a name="v:threadDelay" class="def">threadDelay</a> :: <a href="Data-Int.html#t:Int">Int</a> -> <a href="System-IO.html#t:IO">IO</a> <a href="../ghc-prim-0.2.0.0/GHC-Unit.html#t:-40--41-">()</a></p><div class="doc"><p>Suspends the current thread for a given number of microseconds (GHC only). </p><p>There is no guarantee that the thread will be rescheduled promptly when the delay has expired, but the thread will never continue to run <em>earlier</em> than specified. </p></div></div><div class="top"><p class="src"><a name="v:threadWaitRead" class="def">threadWaitRead</a> :: <a href="System-Posix-Types.html#t:Fd">Fd</a> -> <a href="System-IO.html#t:IO">IO</a> <a href="../ghc-prim-0.2.0.0/GHC-Unit.html#t:-40--41-">()</a></p><div class="doc"><p>Block the current thread until data is available to read on the given file descriptor (GHC only). </p><p>This will throw an <code><a href="System-IO-Error.html#t:IOError">IOError</a></code> if the file descriptor was closed while this thread was blocked. To safely close a file descriptor that has been used with <code><a href="Control-Concurrent.html#v:threadWaitRead">threadWaitRead</a></code>, use <code><a href="GHC-Conc.html#v:closeFdWith">closeFdWith</a></code>. </p></div></div><div class="top"><p class="src"><a name="v:threadWaitWrite" class="def">threadWaitWrite</a> :: <a href="System-Posix-Types.html#t:Fd">Fd</a> -> <a href="System-IO.html#t:IO">IO</a> <a href="../ghc-prim-0.2.0.0/GHC-Unit.html#t:-40--41-">()</a></p><div class="doc"><p>Block the current thread until data can be written to the given file descriptor (GHC only). </p><p>This will throw an <code><a href="System-IO-Error.html#t:IOError">IOError</a></code> if the file descriptor was closed while this thread was blocked. To safely close a file descriptor that has been used with <code><a href="Control-Concurrent.html#v:threadWaitWrite">threadWaitWrite</a></code>, use <code><a href="GHC-Conc.html#v:closeFdWith">closeFdWith</a></code>. </p></div></div><h1 id="g:6">Communication abstractions </h1><div class="top"><p class="src">module <a href="Control-Concurrent-MVar.html">Control.Concurrent.MVar</a></p></div><div class="top"><p class="src">module <a href="Control-Concurrent-Chan.html">Control.Concurrent.Chan</a></p></div><div class="top"><p class="src">module <a href="Control-Concurrent-QSem.html">Control.Concurrent.QSem</a></p></div><div class="top"><p class="src">module <a href="Control-Concurrent-QSemN.html">Control.Concurrent.QSemN</a></p></div><div class="top"><p class="src">module <a href="Control-Concurrent-SampleVar.html">Control.Concurrent.SampleVar</a></p></div><h1 id="g:7">Merging of streams </h1><div class="top"><p class="src"><a name="v:mergeIO" class="def">mergeIO</a> :: [a] -> [a] -> <a href="System-IO.html#t:IO">IO</a> [a]</p></div><div class="top"><p class="src"><a name="v:nmergeIO" class="def">nmergeIO</a> :: [[a]] -> <a href="System-IO.html#t:IO">IO</a> [a]</p></div><div class="doc"><p>The <code><a href="Control-Concurrent.html#v:mergeIO">mergeIO</a></code> and <code><a href="Control-Concurrent.html#v:nmergeIO">nmergeIO</a></code> functions fork one thread for each input list that concurrently evaluates that list; the results are merged into a single output list. </p><p>Note: Hugs does not provide these functions, since they require preemptive multitasking. </p></div><h1 id="g:8">Bound Threads </h1><div class="doc"><p><a name="boundthreads"></a> </p><p>Support for multiple operating system threads and bound threads as described below is currently only available in the GHC runtime system if you use the <em>-threaded</em> option when linking. </p><p>Other Haskell systems do not currently support multiple operating system threads. </p><p>A bound thread is a haskell thread that is <em>bound</em> to an operating system thread. While the bound thread is still scheduled by the Haskell run-time system, the operating system thread takes care of all the foreign calls made by the bound thread. </p><p>To a foreign library, the bound thread will look exactly like an ordinary operating system thread created using OS functions like <code>pthread_create</code> or <code>CreateThread</code>. </p><p>Bound threads can be created using the <code><a href="Control-Concurrent.html#v:forkOS">forkOS</a></code> function below. All foreign exported functions are run in a bound thread (bound to the OS thread that called the function). Also, the <code>main</code> action of every Haskell program is run in a bound thread. </p><p>Why do we need this? Because if a foreign library is called from a thread created using <code><a href="Control-Concurrent.html#v:forkIO">forkIO</a></code>, it won't have access to any <em>thread-local state</em> - state variables that have specific values for each OS thread (see POSIX's <code>pthread_key_create</code> or Win32's <code>TlsAlloc</code>). Therefore, some libraries (OpenGL, for example) will not work from a thread created using <code><a href="Control-Concurrent.html#v:forkIO">forkIO</a></code>. They work fine in threads created using <code><a href="Control-Concurrent.html#v:forkOS">forkOS</a></code> or when called from <code>main</code> or from a <code>foreign export</code>. </p><p>In terms of performance, <code><a href="Control-Concurrent.html#v:forkOS">forkOS</a></code> (aka bound) threads are much more expensive than <code><a href="Control-Concurrent.html#v:forkIO">forkIO</a></code> (aka unbound) threads, because a <code><a href="Control-Concurrent.html#v:forkOS">forkOS</a></code> thread is tied to a particular OS thread, whereas a <code><a href="Control-Concurrent.html#v:forkIO">forkIO</a></code> thread can be run by any OS thread. Context-switching between a <code><a href="Control-Concurrent.html#v:forkOS">forkOS</a></code> thread and a <code><a href="Control-Concurrent.html#v:forkIO">forkIO</a></code> thread is many times more expensive than between two <code><a href="Control-Concurrent.html#v:forkIO">forkIO</a></code> threads. </p><p>Note in particular that the main program thread (the thread running <code>Main.main</code>) is always a bound thread, so for good concurrency performance you should ensure that the main thread is not doing repeated communication with other threads in the system. Typically this means forking subthreads to do the work using <code><a href="Control-Concurrent.html#v:forkIO">forkIO</a></code>, and waiting for the results in the main thread. </p></div><div class="top"><p class="src"><a name="v:rtsSupportsBoundThreads" class="def">rtsSupportsBoundThreads</a> :: <a href="Data-Bool.html#t:Bool">Bool</a></p><div class="doc"><p><code><a href="Data-Bool.html#v:True">True</a></code> if bound threads are supported. If <code>rtsSupportsBoundThreads</code> is <code><a href="Data-Bool.html#v:False">False</a></code>, <code><a href="Control-Concurrent.html#v:isCurrentThreadBound">isCurrentThreadBound</a></code> will always return <code><a href="Data-Bool.html#v:False">False</a></code> and both <code><a href="Control-Concurrent.html#v:forkOS">forkOS</a></code> and <code><a href="Control-Concurrent.html#v:runInBoundThread">runInBoundThread</a></code> will fail. </p></div></div><div class="top"><p class="src"><a name="v:forkOS" class="def">forkOS</a> :: <a href="System-IO.html#t:IO">IO</a> <a href="../ghc-prim-0.2.0.0/GHC-Unit.html#t:-40--41-">()</a> -> <a href="System-IO.html#t:IO">IO</a> <a href="Control-Concurrent.html#t:ThreadId">ThreadId</a></p><div class="doc"><p>Like <code><a href="Control-Concurrent.html#v:forkIO">forkIO</a></code>, this sparks off a new thread to run the <code><a href="System-IO.html#t:IO">IO</a></code> computation passed as the first argument, and returns the <code><a href="Control-Concurrent.html#t:ThreadId">ThreadId</a></code> of the newly created thread. </p><p>However, <code><a href="Control-Concurrent.html#v:forkOS">forkOS</a></code> creates a <em>bound</em> thread, which is necessary if you need to call foreign (non-Haskell) libraries that make use of thread-local state, such as OpenGL (see <a href="Control-Concurrent.html#boundthreads">Control.Concurrent</a>). </p><p>Using <code><a href="Control-Concurrent.html#v:forkOS">forkOS</a></code> instead of <code><a href="Control-Concurrent.html#v:forkIO">forkIO</a></code> makes no difference at all to the scheduling behaviour of the Haskell runtime system. It is a common misconception that you need to use <code><a href="Control-Concurrent.html#v:forkOS">forkOS</a></code> instead of <code><a href="Control-Concurrent.html#v:forkIO">forkIO</a></code> to avoid blocking all the Haskell threads when making a foreign call; this isn't the case. To allow foreign calls to be made without blocking all the Haskell threads (with GHC), it is only necessary to use the <code>-threaded</code> option when linking your program, and to make sure the foreign import is not marked <code>unsafe</code>. </p></div></div><div class="top"><p class="src"><a name="v:isCurrentThreadBound" class="def">isCurrentThreadBound</a> :: <a href="System-IO.html#t:IO">IO</a> <a href="Data-Bool.html#t:Bool">Bool</a></p><div class="doc"><p>Returns <code><a href="Data-Bool.html#v:True">True</a></code> if the calling thread is <em>bound</em>, that is, if it is safe to use foreign libraries that rely on thread-local state from the calling thread. </p></div></div><div class="top"><p class="src"><a name="v:runInBoundThread" class="def">runInBoundThread</a> :: <a href="System-IO.html#t:IO">IO</a> a -> <a href="System-IO.html#t:IO">IO</a> a</p><div class="doc"><p>Run the <code><a href="System-IO.html#t:IO">IO</a></code> computation passed as the first argument. If the calling thread is not <em>bound</em>, a bound thread is created temporarily. <code>runInBoundThread</code> doesn't finish until the <code><a href="System-IO.html#t:IO">IO</a></code> computation finishes. </p><p>You can wrap a series of foreign function calls that rely on thread-local state with <code>runInBoundThread</code> so that you can use them without knowing whether the current thread is <em>bound</em>. </p></div></div><div class="top"><p class="src"><a name="v:runInUnboundThread" class="def">runInUnboundThread</a> :: <a href="System-IO.html#t:IO">IO</a> a -> <a href="System-IO.html#t:IO">IO</a> a</p><div class="doc"><p>Run the <code><a href="System-IO.html#t:IO">IO</a></code> computation passed as the first argument. If the calling thread is <em>bound</em>, an unbound thread is created temporarily using <code><a href="Control-Concurrent.html#v:forkIO">forkIO</a></code>. <code>runInBoundThread</code> doesn't finish until the <code><a href="System-IO.html#t:IO">IO</a></code> computation finishes. </p><p>Use this function <em>only</em> in the rare case that you have actually observed a performance loss due to the use of bound threads. A program that doesn't need it's main thread to be bound and makes <em>heavy</em> use of concurrency (e.g. a web server), might want to wrap it's <code>main</code> action in <code>runInUnboundThread</code>. </p></div></div><h1 id="g:9">GHC's implementation of concurrency </h1><div class="doc"><p>This section describes features specific to GHC's implementation of Concurrent Haskell. </p></div><h2 id="g:10">Haskell threads and Operating System threads </h2><div class="doc"><p><a name="osthreads"></a> In GHC, threads created by <code><a href="Control-Concurrent.html#v:forkIO">forkIO</a></code> are lightweight threads, and are managed entirely by the GHC runtime. Typically Haskell threads are an order of magnitude or two more efficient (in terms of both time and space) than operating system threads. </p><p>The downside of having lightweight threads is that only one can run at a time, so if one thread blocks in a foreign call, for example, the other threads cannot continue. The GHC runtime works around this by making use of full OS threads where necessary. When the program is built with the <code>-threaded</code> option (to link against the multithreaded version of the runtime), a thread making a <code>safe</code> foreign call will not block the other threads in the system; another OS thread will take over running Haskell threads until the original call returns. The runtime maintains a pool of these <em>worker</em> threads so that multiple Haskell threads can be involved in external calls simultaneously. </p><p>The <a href="System-IO.html">System.IO</a> library manages multiplexing in its own way. On Windows systems it uses <code>safe</code> foreign calls to ensure that threads doing I/O operations don't block the whole runtime, whereas on Unix systems all the currently blocked I/O requests are managed by a single thread (the <em>IO manager thread</em>) using <code>select</code>. </p><p>The runtime will run a Haskell thread using any of the available worker OS threads. If you need control over which particular OS thread is used to run a given Haskell thread, perhaps because you need to call a foreign library that uses OS-thread-local state, then you need bound threads (see <a href="Control-Concurrent.html#boundthreads">Control.Concurrent</a>). </p><p>If you don't use the <code>-threaded</code> option, then the runtime does not make use of multiple OS threads. Foreign calls will block all other running Haskell threads until the call returns. The <a href="System-IO.html">System.IO</a> library still does multiplexing, so there can be multiple threads doing I/O, and this is handled internally by the runtime using <code>select</code>. </p></div><h2 id="g:11">Terminating the program </h2><div class="doc"><p>In a standalone GHC program, only the main thread is required to terminate in order for the process to terminate. Thus all other forked threads will simply terminate at the same time as the main thread (the terminology for this kind of behaviour is "daemonic threads"). </p><p>If you want the program to wait for child threads to finish before exiting, you need to program this yourself. A simple mechanism is to have each child thread write to an <code><a href="Control-Concurrent-MVar.html#t:MVar">MVar</a></code> when it completes, and have the main thread wait on all the <code><a href="Control-Concurrent-MVar.html#t:MVar">MVar</a></code>s before exiting: </p><pre> myForkIO :: IO () -> IO (MVar ()) myForkIO io = do mvar <- newEmptyMVar forkIO (io `finally` putMVar mvar ()) return mvar </pre><p>Note that we use <code><a href="Control-Exception-Base.html#v:finally">finally</a></code> from the <a href="Control-Exception.html">Control.Exception</a> module to make sure that the <code><a href="Control-Concurrent-MVar.html#t:MVar">MVar</a></code> is written to even if the thread dies or is killed for some reason. </p><p>A better method is to keep a global list of all child threads which we should wait for at the end of the program: </p><pre> children :: MVar [MVar ()] children = unsafePerformIO (newMVar []) waitForChildren :: IO () waitForChildren = do cs <- takeMVar children case cs of [] -> return () m:ms -> do putMVar children ms takeMVar m waitForChildren forkChild :: IO () -> IO ThreadId forkChild io = do mvar <- newEmptyMVar childs <- takeMVar children putMVar children (mvar:childs) forkIO (io `finally` putMVar mvar ()) main = later waitForChildren $ ... </pre><p>The main thread principle also applies to calls to Haskell from outside, using <code>foreign export</code>. When the <code>foreign export</code>ed function is invoked, it starts a new main thread, and it returns when this main thread terminates. If the call causes new threads to be forked, they may remain in the system after the <code>foreign export</code>ed function has returned. </p></div><h2 id="g:12">Pre-emption </h2><div class="doc"><p>GHC implements pre-emptive multitasking: the execution of threads are interleaved in a random fashion. More specifically, a thread may be pre-empted whenever it allocates some memory, which unfortunately means that tight loops which do no allocation tend to lock out other threads (this only seems to happen with pathological benchmark-style code, however). </p><p>The rescheduling timer runs on a 20ms granularity by default, but this may be altered using the <code>-i<n></code> RTS option. After a rescheduling "tick" the running thread is pre-empted as soon as possible. </p><p>One final note: the <code>aaaa</code> <code>bbbb</code> example may not work too well on GHC (see Scheduling, above), due to the locking on a <code>System.IO.Handle</code>. Only one thread may hold the lock on a <code>System.IO.Handle</code> at any one time, so if a reschedule happens while a thread is holding the lock, the other thread won't be able to run. The upshot is that the switch from <code>aaaa</code> to <code>bbbbb</code> happens infrequently. It can be improved by lowering the reschedule tick period. We also have a patch that causes a reschedule whenever a thread waiting on a lock is woken up, but haven't found it to be useful for anything other than this example :-) </p></div></div></div><div id="footer"><p>Produced by <a href="http://www.haskell.org/haddock/">Haddock</a> version 2.9.2</p></div></body></html>