Advertisement
Guest User

Untitled

a guest
May 24th, 2015
234
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.98 KB | None | 0 0
  1. {-# LANGUAGE JavaScriptFFI #-}
  2. module Main where
  3.  
  4. import Control.Concurrent
  5. import Control.Concurrent.MVar
  6. import Control.Monad
  7.  
  8. -- | Very simple, no exception safety. Intended for async JS functions.
  9. parallel :: [IO a] -> IO [a]
  10. parallel fs = do
  11. vars <- forM fs $ \f -> do
  12. v <- newEmptyMVar
  13. _ <- forkIO $ f >>= putMVar v
  14. return v
  15. mapM takeMVar vars
  16.  
  17. -- | Just your average async JS function.
  18. foreign import javascript interruptible
  19. " console.log('Starting ' + $1); \
  20. \ setTimeout(function(){ \
  21. \ console.log('Ending ' + $1); \
  22. \ $c($1 * 100); \
  23. \ }, $1 * 1000); "
  24. seconds :: Int -> IO Int
  25.  
  26. -- | Waits a maximum of 5 seconds for the action to finish.
  27. timeout :: IO a -> IO (Maybe a)
  28. timeout f = do
  29. v <- newEmptyMVar
  30. _ <- forkIO $ f >>= putMVar v . Just
  31. _ <- forkIO $ threadDelay 5000000 >> putMVar v Nothing
  32. takeMVar v
  33.  
  34. main :: IO ()
  35. main = do
  36. parallel (map timeout [seconds 1, seconds 2, seconds 10]) >>= print
  37. print "done"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement