[Haskell-cafe] Re: Waiting for thread to finish

Don Stewart dons at galois.com
Tue Nov 27 15:09:39 EST 2007


briqueabraque:
> >> Hi,
> >>
> >> After I have spawned a thread with 'forkIO',
> >> how can I check if that thread work has
> >> finished already?  Or wait for it?
> >>
> 
> > The best way to do this is using
> > Control.Exception.finally: (...)
> >
> > These techniques are needed because forkIO is a
> > very lightweight threading mechanism.  Adding
> > precisely the features you need makes for good
> > performance control, as seen in the great
> > computer language shootout benchmarks.
> 
> Changing ugly code for bad performance is not that
> usual in Haskell code :(

I think you misunderstand Chris' remark. He's saying that MVars and forkIO
give you bot clean control, and high performance.

This code seems quite elegant, for the job you were asking:

    import Control.Concurrent
    import Control.Exception

    main = do
        done <- run (print (last [1..100000000]))
        print "Waiting...."
        takeMVar done
        print "OK."
     where
        run f = do
            x <- newEmptyMVar
            forkIO (f `finally` putMVar x ())
            return x

And the lovely thread-ring benchmark, is also very nice:

    http://shootout.alioth.debian.org/gp4/benchmark.php?test=threadring&lang=all

Where the Haskell code is both the shortest, and fastest.
Beautiful code can be very efficient.

-- Don


More information about the Haskell-Cafe mailing list