Created
January 9, 2014 01:08
-
-
Save jamwt/8327681 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Control.Concurrent (forkIO, threadDelay) | |
import Control.Concurrent.Chan (newChan, readChan, writeChan) | |
import Control.Monad (replicateM_, replicateM, mapM_) | |
import Data.Function (on) | |
import Data.List as List | |
data MapItem a = | |
Item Int a | |
| Done | |
pmap :: (a -> IO b) -> Int -> [a] -> IO [b] | |
pmap func concurrency as = do | |
inChan <- newChan | |
outChan <- newChan | |
replicateM_ concurrency $ forkIO $ runThread inChan outChan | |
mapM_ (\(i, a)-> writeChan inChan $ Item i a) $ zip [0..] as | |
replicateM_ concurrency $ writeChan inChan Done | |
unsortedResults <- replicateM (length as) $ readChan outChan | |
return $ (map snd . List.sortBy (compare `on` fst)) unsortedResults | |
where | |
runThread inChan outChan = do | |
next <- readChan inChan | |
case next of | |
Item idx a -> do | |
b <- func a | |
writeChan outChan (idx, b) | |
runThread inChan outChan | |
Done -> return () | |
main = do | |
pmap (\x-> threadDelay 10000 >> print x) 100 [0..5000] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment