[Haskell-cafe] Re: Waiting for thread to finish
dons at galois.com
Tue Nov 27 15:09:39 EST 2007
> >> 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:
main = do
done <- run (print (last [1..100000000]))
run f = do
x <- newEmptyMVar
forkIO (f `finally` putMVar x ())
And the lovely thread-ring benchmark, is also very nice:
Where the Haskell code is both the shortest, and fastest.
Beautiful code can be very efficient.
More information about the Haskell-Cafe