6

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

示例(伪代码):

thread1 = spark $ long_running some_arg1
thread2 = spark $ long_running some_arg2
result = first_done thread1 thread2 -- Maybe even first_done [thread1, thread2]?
4

3 回答 3

17

async包执行此操作,现在是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)
于 2012-12-31T20:28:29.513 回答
3

如果你想杀死更长的运行线程,你可以使用:http ://hackage.haskell.org/package/unamb

否则,您可以做与 unamb 相同的事情,但忽略 killThread。

于 2012-12-31T20:23:27.920 回答
2

如果您使用IO线程,您还可以使用最新的parallel-io包,特别是parallelFirst

于 2013-01-01T12:19:33.320 回答