Skip to content

Instantly share code, notes, and snippets.

@scan
Created January 26, 2013 15:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save scan/4642914 to your computer and use it in GitHub Desktop.
Save scan/4642914 to your computer and use it in GitHub Desktop.
import Control.Concurrent.Chan (Chan, newChan)
import qualified Data.Map as M
import Control.Concurrent.STM (TVar, readTVar, writeTVar)
type Id = Integer
getOrCreateChannel :: (MonadIO m) => Id -> TVar (M.Map Id (Chan a)) -> m (Chan a)
getOrCreateChannel cid t = liftIO $ do
nchan <- newChan
atomically $ do
chans <- readTVar t
case M.lookup cid chans of
(Just c) -> return c
Nothing -> do
writeTVar t $ M.insert cid nchan chans
return nchan
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment