Get result from first thread completed

Let's say I want to compute two lengthy processes in two separate threads in Haskell. However, I only care about the result of the first. How can I do it?

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]? 
+6
source share
3 answers

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) 
+17
source

If you want a longer workflow to be killed, you can use: http://hackage.haskell.org/package/unamb

Otherwise, you can do the same as unamb, but not leave killThread.

+3
source

If you work with IO streams, you can also use the latest parallel-io package, in particular parallelFirst .

+2
source

All Articles