至少包中的Par
monad 和策略parallel
只允许构建纯粹的、无条件的并行系统,这些系统看起来很漂亮:
一个
/ \
公元前
\ /\
德
\ ...
虽然在一般情况下,您确实需要不纯的线程间通信:
solve :: Tree a -> Maybe a
smartPartition :: Tree a -> Int -> [[Tree a]]
smartPartition tree P = ... -- split the tree in fairly even chunks,
-- one per each machine core
solveP :: Tree a -> IO (Maybe a)
solveP tree = do
resRef <- newIORef Nothing
results <- parallel (map work (smartPartition tree))
return (msum results)
where work [] = return Nothing
work (t:ts) = do
res <- readIORef resRef
if (isJust res) then (return res) else do
let tRes = solve t
if (isNothing tRes) then (work ts) else do
writeIORef tRes
return tRes
但是,如果您的单叶计算足够且同样昂贵,则取消策略不应该(我不确定)会大大损害性能:
partitionLeafs :: Tree a -> Int -> [[Tree a]]
solveP :: Tree a -> Maybe a
solveP = msum . map step . transpose . partitionLeafs
where step = msum . parMap rdeepseq solve
PS我觉得我对问题领域的理解并不比你好(至少),所以你可能已经知道以上所有内容。我写了这个答案来展开讨论,因为这个问题对我来说很有趣。