假设我想在 Haskell 的两个单独线程中计算两个长时间运行的进程。但是,我只关心第一个完成的结果。我该怎么做?
示例(伪代码):
thread1 = spark $ long_running some_arg1
thread2 = spark $ long_running some_arg2
result = first_done thread1 thread2 -- Maybe even first_done [thread1, thread2]?
假设我想在 Haskell 的两个单独线程中计算两个长时间运行的进程。但是,我只关心第一个完成的结果。我该怎么做?
示例(伪代码):
thread1 = spark $ long_running some_arg1
thread2 = spark $ long_running some_arg2
result = first_done thread1 thread2 -- Maybe even first_done [thread1, thread2]?
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)
如果你想杀死更长的运行线程,你可以使用:http ://hackage.haskell.org/package/unamb
否则,您可以做与 unamb 相同的事情,但忽略 killThread。
如果您使用IO
线程,您还可以使用最新的parallel-io包,特别是parallelFirst。