Skip to content

Instantly share code, notes, and snippets.

@jamwt
Created January 9, 2014 01:08
Show Gist options
  • Save jamwt/8327681 to your computer and use it in GitHub Desktop.
Save jamwt/8327681 to your computer and use it in GitHub Desktop.
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