Take the 2-minute tour ×

Say I want to compute two long running processes in two separate threads in Haskell. However, I only care about the result from the first one done. How would I do this?

Example (pseudo code):

thread1 = spark $ long_running some_arg1
thread2 = spark $ long_running some_arg2
result = first_done thread1 thread2 -- Maybe even first_done [thread1, thread2]?
share|improve this question
add comment

3 Answers

up vote 15 down vote accepted

The async package does this, and is now part of the Haskell Platform.

import Control.Concurrent.Async
import Control.Concurrent (threadDelay)

main :: IO ()
main = do
  x <- async (threadDelay 2000000 >> return 1)
  y <- async (threadDelay 1000000 >> return 2)
  (_, res) <- waitAnyCancel [x, y]
  print (res :: Int)
share|improve this answer
This is exactly what I was looking for, thanks! –  bheklilr Dec 31 '12 at 21:06
add comment

If you'd work with IO threads, you could also use the latest parallel-io package, in particular parallelFirst.

share|improve this answer
add comment

If you want the longer running thread killed you can use: http://hackage.haskell.org/package/unamb

Otherwise you could do the same thing as unamb but leave out the killThread.

share|improve this answer
add comment

Your Answer


