Revision as of 03:24, 3 September 2008

This site attempts to document all our available information on
exploiting such hardware with Haskell.

Throughout, we focus on exploiting shared-memory SMP systems, with aim of lowering absolute wall clock times. The machines we target are typical 2x to 32x desktop multicore machine, on which vanilla GHC will run.

1 Introduction

To get an idea of what we aim to do -- reduce running times by exploiting more cores -- here's a naive "hello, world" of parallel programs: parallel, naive fib. It simply tells us whether or not the SMP runtime is working:

2 Thread primitives

For explicit concurrency and/or parallelism, Haskell implementations have a light-weight thread system that schedules logical threads on the available operating system threads. These light and cheap threads can be created with forkIO. Full OS threads will not be discussed here beyond saying they pose a significantly higher overhead, but you create them using forkOS if truly needed.

forkIO ::IO()->IO ThreadId

Lets take a simple Haskell application that hashes two files and prints the result:

Now we have a rough program with great performance boost - which is expected given the trivially parallel computation.

But wait! You say there is a bug? Two, actually. One is that if the main thread is finished hashing fileB first, the program will exit before the child thread is done with fileA. The second is a potential for garbled output due to two threads writing to stdout. Both these problems can be solved using some inter-thread communication - we'll pick this example up in the MVar section.

3 Synchronisation with locks

Previously in the forkIO example we developed a program to hash two files in parallel and ended with a couple small bugs because the program terminated prematurely (the main thread would exit when done). A second issue was that threads can conflict with each others use of stdout.

Locking mutable variables (MVars) can be used to great effect not only for communicating values (such as the resulting string for a single function to print) but it is also common for programmers to use their locking features as a signaling mechanism.

MVars are a polymorphic mutable variables that might or might not contain a value at any given time. This example will only use the following three functions:

While they are fairly self-explanitory it should be noted that takeMVar will block until the MVar is non-empty and putMVar will block until the current MVar is empty. Taking an MVar will leave the MVar empty when returning the value.

Lets now generalize our forkIO program to operate on any number of files, block until the hashing is complete, and print all the results from just one thread so no stdout garbling occurs.