从第一个线程完成获得结果

bhe*_*ilr 6 haskell

假设我想在Haskell中的两个独立线程中计算两个长时间运行的进程.但是,我只关心第一个完成的结果.我该怎么做?

示例(伪代码):

thread1 = spark $ long_running some_arg1
thread2 = spark $ long_running some_arg2
result = first_done thread1 thread2 -- Maybe even first_done [thread1, thread2]?
Run Code Online (Sandbox Code Playgroud)

Nat*_*ell 17

异步包这样做,并且现在是一部分哈斯克尔平台.

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)
Run Code Online (Sandbox Code Playgroud)