Zum Inhalt springen

Benutzer:Dirk Hünniger/mediawiki2latex/Parrallel Download

Aus Wikibooks

Downloads are parralalized. The maxmimum number of parralell opeations is defined. The concept used here is similar to java Future Type. Usually an function takes some input parameters and generates and output. In most cases the paramerters of the function have to be full calculated before the function is called. In haskell this concept is not fully true anymode due to the concept of lazyness. Still IO Operations usually happen in order. We also uses laziness in IO Operations, but making uses of MVar. An MVar is a threadsafe container for an objekt. In the beginning it is empty, if we try the read it out code block until an other thread fills. So lets look at function taking to integers and returning is sum. Furthermore lets assume a time consuming IO Operation is needed to calculate the sum. The function might look like this:

add :: Int -> Int -> IO Int
add a b = do threadDelay 1000
             return a + b

If we now call this function our thread will block for a while. And if we got many of these functions to call in our program we will gain a significant speedup when running in them parralel. The trick we are going to do now, is not just to rewrite this single function but to develop a wrapper the will transform all funtions of two parameters to the paralellized versions.


liftA2 :: MVar Int -> (a -> b -> IO c) -> MVar a -> MVar b -> IO (MVar c)
liftA2 vv f x y
  = do var <- newEmptyMVar
       _ <- myFork vv (go var)
       return var
  where go v
          = do xx <- readMVar x
               yy <- readMVar y
               result <- f xx yy
               putMVar v result

We addinitonaly need the number of threads currently running as first parameter. We create a new MVar, fork a new thread the will later on fill the MVar and return the MVar immidiatly, so the code that called us runs on immediately. User new thread does a blocking read in order to determine the two parameters passed to the function as MVars, calles the standard version of the function and finally writes the returned result into the MVar