Guest User

Untitled

a guest
May 24th, 2018
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.04 KB | None | 0 0
  1. {-# LANGUAGE PackageImports #-}
  2.  
  3. module EasyPool
  4. ( EasyPool
  5. , withEasyPool
  6. , newEasyPool
  7. ) where
  8.  
  9. import Pool
  10. import Control.Monad.STM
  11. import Control.Concurrent.STM.TVar
  12. import Control.Monad.IO.Class
  13. import "MonadCatchIO-transformers" Control.Monad.CatchIO
  14.  
  15. data EasyPool r m = EasyPool
  16. { epPool :: Pool r
  17. , epMake :: m (Maybe r)
  18. }
  19.  
  20. withEasyPool :: MonadCatchIO m => EasyPool r m -> (r -> m a) -> m (Maybe a)
  21. withEasyPool (EasyPool pool mk) = withPool pool mk
  22.  
  23. newEasyPool :: MonadCatchIO m => Int -> m r -> m (EasyPool r m)
  24. newEasyPool count mk = do
  25. pool <- new
  26. texist <- liftIO $ newTVarIO 0
  27. return $ EasyPool pool $ mk' texist
  28. where
  29. mk' texist = do
  30. exist <- liftIO $ atomically $ readTVar texist
  31. if exist >= count
  32. then return Nothing
  33. else do
  34. r <- mk
  35. liftIO $ atomically $ do
  36. exist <- readTVar texist
  37. if exist >= count
  38. then return Nothing
  39. else return $ Just r
Add Comment
Please, Sign In to add comment