我的理解par
是它将在另一个核心中创建一个线程来执行。
但是我未能通过以下测试代码证明这种理解,因为显示的结果似乎只有一个线程正在运行。
你能帮我弄清楚这里有什么问题吗?
import Control.Monad
import Control.Parallel
import Control.Concurrent
import System.IO.Unsafe
fib :: Int -> Int
fib 0 = 1
fib 1 = 1
fib n = (fib (n-1)) + (fib (n - 2))
test :: String -> [Int] -> IO ()
test _ [] = return ()
test name (a:xs) = do
tid <- myThreadId
print $ (show tid) ++ "==>" ++ (show a) ++ "==>" ++ (show $ fib a) ++ "==>" ++ name
x `par` y
where x = test "2" xs
y = test "3" (tail xs)
main = test "1" [10..35]
编译:
ghc --make -threaded -rtsopts test-par.hs
time ./test-par +RTS -N2
结果
"ThreadId 3==>10==>89==>1"
"ThreadId 3==>12==>233==>3"
"ThreadId 3==>14==>610==>3"
"ThreadId 3==>16==>1597==>3"
"ThreadId 3==>18==>4181==>3"
"ThreadId 3==>20==>10946==>3"
"ThreadId 3==>22==>28657==>3"
"ThreadId 3==>24==>75025==>3"
"ThreadId 3==>26==>196418==>3"
"ThreadId 3==>28==>514229==>3"
"ThreadId 3==>30==>1346269==>3"
"ThreadId 3==>32==>3524578==>3"
"ThreadId 3==>34==>9227465==>3"
real 0m1.131s
user 0m0.668s
sys 0m0.492s
我有几个核心?
cat /proc/cpuinfo | grep processor | wc -l
2
- - - - - - - - - - - - - - - - 更新
我认为Simon Marlow 的这篇论文对于这样的新手问题是一个很好的参考。