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]?
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)
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.
If you'd work with IO
threads, you could also use the latest parallel-io package, in particular parallelFirst.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With