Contents

1 Parallel and Concurrent Programming in GHC

This page contains notes and information about how to write concurrent programs in GHC.

You may be interested in parallelism (speeding up pure functions) instead. Have a look there too.

GHC provides multi-scale support for parallel programming, from very fine-grained, small "sparks", to coarse-grained explicit threads and locks, along with other models of concurrent and parallel programming, including actors, CSP-style concurrency, nested data parallelism and Intel Concurrent Collections. Synchronization between tasks is possible via messages, regular Haskell variables, MVar shared state or transactional memory.

See "Real World Haskell" chapter 24, for an introduction to the most common forms of concurrent and parallel programming in GHC.

The most important (as of 2010) to get to know are the basic "concurrent Haskell" model of threads using forkIO and MVars, the use of transactional memory via STM, implicit parallelism via sparks and, if you're interested in scientific programming specifically, nested data parallelism in Haskell.

1.1 Starting points

Basic concurrency: forkIO and MVars.

Software Transactional Memory (STM) is a new way to coordinate concurrent threads. There's a separate Wiki page devoted to STM.

1.3 Multicore GHC

Run the program with +RTS -N2 to use 2 threads, for example (RTS stands for runtime system; see the GHC users' guide). You should use a -N value equal to the number of CPU cores on your machine (not including Hyper-threading cores). As of GHC v6.12, you can leave off the number of cores and all available cores will be used (you still need to pass -N however, like so: +RTS -N).

Concurrent threads (forkIO) will run in parallel, and you can also use the par combinator and Strategies from the Control.Parallel.Strategies module to create parallelism.