[Haskell-cafe] Re: MVar and Par ..

Luke Palmer lrpalmer at gmail.com
Tue Dec 16 07:57:35 EST 2008

On Tue, Dec 16, 2008 at 5:54 AM, Luke Palmer <lrpalmer at gmail.com> wrote:

> Okay, that's a bit clearer.  Control.Parallel is not what you want; that is
> for parallelizing pure code (and is very nice inside its little domain).
> But you want concurrent code: multiple threads that change state at the same
> time.  That is in Control.Concurrent.
> In particular, the "shared variable" is Data.IORef.
> Simple example from which you should be able to extrapolate.

Apologies, this code doesn't compile.  Here's the fixed version:

import Control.Concurrent
import Control.Concurrent.MVar
import Data.IORef

threadBody var = do
    x <- readIORef var
    writeIORef var (x+1)

main = do
    var <- newIORef 0
    -- spawn two threads
    forkIO (threadBody var)
    forkIO (threadBody var)

    -- look at the value of the variable
    x <- readIORef var
    print x
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20081216/4e1cf11c/attachment.htm

More information about the Haskell-Cafe mailing list