Created
February 19, 2013 11:53
-
-
Save supki/4985176 to your computer and use it in GitHub Desktop.
Asynchronous jobs up to N simultaniously
This file contains hidden or 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
| {-# LANGUAGE ViewPatterns #-} | |
| module Main where | |
| import Control.Applicative | |
| import Control.Concurrent | |
| import Control.Concurrent.Async | |
| import Data.List (delete) | |
| import System.Environment (getArgs) | |
| main :: IO () | |
| main = do | |
| j:js:_ <- map read <$> getArgs | |
| run j $ map (job_wrapper . job) [1..js] | |
| run :: Int -> [IO a] -> IO () | |
| run n (splitAt n -> (ys, zs)) = mapM async ys >>= go zs | |
| where | |
| go :: [IO a] -> [Async a] -> IO () | |
| go [] [] = return () | |
| go [] as = do | |
| (a, _) <- waitAny as | |
| go [] (delete a as) | |
| go (x:xs) as = do | |
| (a, _) <- waitAny as | |
| b <- async x | |
| go xs (b : delete a as) | |
| job_wrapper :: IO () -> IO () | |
| job_wrapper a = do | |
| print "Start job concurrently" | |
| a | |
| print "Stop job" | |
| job :: Int -> IO () | |
| job n = print n >> threadDelay (n * 200000) |
Author
supki
commented
Feb 19, 2013
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment