Tôi đã làm việc thông qua các bài tập lập trình song song xác định của Andre Loh trong các bài tập haskell. Tôi đã cố gắng để chuyển đổi mã tuần tự N-Queens thành song song bằng cách sử dụng chiến lược, nhưng tôi nhận thấy rằng mã song song chạy chậm hơn nhiều so với mã tuần tự và cũng có lỗi với không đủ ngăn xếp.Suy thoái khi sử dụng các chiến lược song song trong Haskell
Đây là mã cho song song N-Queens,
import Control.Monad
import System.Environment
import GHC.Conc
import Control.Parallel.Strategies
import Data.List
import Data.Function
type PartialSolution = [Int] -- per column, list the row the queen is in
type Solution = PartialSolution
type BoardSize = Int
chunk :: Int -> [a] -> [[a]]
chunk n [] = []
chunk n xs = case splitAt n xs of
(ys, zs) -> ys : chunk n zs
-- Generate all solutions for a given board size.
queens :: BoardSize -> [Solution]
--queens n = iterate (concatMap (addQueen n)) [[]] !! n
queens n = iterate (\l -> concat (map (addQueen n) l `using` parListChunk (n `div` numCapabilities) rdeepseq)) [[]] !! n
-- Given the size of the problem and a partial solution for the
-- first few columns, find all possible assignments for the next
-- column and extend the partial solution.
addQueen :: BoardSize -> PartialSolution -> [PartialSolution]
addQueen n s = [ x : s | x <- [1..n], safe x s 1 ]
-- Given a row number, a partial solution and an offset, check
-- that a queen placed at that row threatens no queen in the
-- partial solution.
safe :: Int -> PartialSolution -> Int -> Bool
safe x [] n = True
safe x (c:y) n = x /= c && x /= c + n && x /= c - n && safe x y (n + 1)
main = do
[n] <- getArgs
print $ length $ queens (read n)
Dòng (\l -> concat (map (addQueen n) l using parListChunk (n div numCapabilities) rdeepseq))
là những gì tôi đã thay đổi từ mã gốc. Tôi đã nhìn thấy giải pháp của Simon Marlow nhưng tôi muốn biết lý do cho sự chậm lại và lỗi trong mã của tôi.
Xin cảm ơn trước.
Làm sao bạn biên dịch và chạy? – is7s
Bạn đang biên dịch với '-O2' và đang chạy với' -readed -Nn' (trong đó 'n' là số cpu của bạn?) –
Lưu ý rằng' -readed' là một tùy chọn biên dịch thời gian, không phải là tùy chọn thời gian chạy. Ngoài ra, khi nào bạn trở lại với Baily's, Don? Các vòi nước bỏ lỡ bạn. –