[Haskell-cafe] multithreading speedup

Stefan O'Rear stefanor at cox.net
Fri Apr 13 18:33:44 EDT 2007

On Sat, Apr 14, 2007 at 12:27:10AM +0200, Fawzi Mohamed wrote:
> I was trying to speed up a program that I wrote and so I thought  
> about using multiple threads.
> I  have a quite easy parallel program and I did the following
> do
>       subRes <- MVar.newMVar []
>       putStrLn "starting threads"
>       subV <- flip mapM [0 .. (nThreads - 1)] $
>               ( \i -> do
>                   subR <- MVar.newEmptyMVar
>                   let writeRes r = do { MVar.putMVar subR r }
>                   forkOS (do
>                            let r=eval (startData !! i)
>                            writeRes $! r
>                            putStr $ "writtenRes")
>                   return subR
>               )
>       putStrLn "started threads"
>       toFold <- mapM MVar.takeMVar subV
>       putStrLn "about to fold"
>       return $ foldl1 mergeRes toFold
> I know that the threads really calculate what I want, and as soon as  
> they are finished I get the result.
> The problem is that I have no speed up, the time is basically the sum  
> of the time for the two threads.
> I thought that ghc now would take advantage of the two cpus if I  
> compiled with -threaded.
> Am I wrong, do I need some special flag, a newer version of the  
> compiler (I have 6.6.20070129), or it is just normal?

./MyProgram +RTS -N2

where N is your CPU count.

(that said, DO NOT USE THREADS IF AT ALL POSSIBLE, they are ugly and
cause heisenbugs, if you want paralelism `par` from Control.Parallel
is to be preferred if at all possible since it is deterministic)


More information about the Haskell-Cafe mailing list