Skip to content

Instantly share code, notes, and snippets.

@ssadler
Created July 13, 2014 13:27
Show Gist options
  • Save ssadler/6289a356f01c6a376855 to your computer and use it in GitHub Desktop.
Save ssadler/6289a356f01c6a376855 to your computer and use it in GitHub Desktop.
module Actors where
import Control.Concurrent.MVar
import Control.Concurrent (forkIO)
import Control.Monad (forever, replicateM)
type PoolQuery a b = a -> IO b
type PoolActor a = MVar (PoolQuery a ())
forkPoolActors :: (IO a) -> Int -> IO (PoolActor a)
forkPoolActors construct n = do
qbox <- newEmptyMVar
replicateM n $ do
forkIO $ do
res <- construct
forever $ do
query <- takeMVar qbox
query res
return ()
return qbox
withResource :: PoolActor a -> PoolQuery a b -> IO b
withResource qbox query = do
abox <- newEmptyMVar
putMVar qbox $ \res -> query res >>= putMVar abox
takeMVar abox
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment