Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get result from first thread completed

Tags:

haskell

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]?
like image 467
bheklilr Avatar asked Dec 31 '12 20:12

bheklilr


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)
like image 192
Nathan Howell Avatar answered Nov 09 '22 21:11

Nathan Howell


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.

like image 25
aavogt Avatar answered Nov 09 '22 19:11

aavogt


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

like image 2
Petr Avatar answered Nov 09 '22 20:11

Petr