Skip to content

Instantly share code, notes, and snippets.

@NathanHowell
Forked from scan/chan.hs
Last active December 11, 2015 19:19
Show Gist options
  • Save NathanHowell/4647598 to your computer and use it in GitHub Desktop.
Save NathanHowell/4647598 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
import Control.Monad.Trans (MonadIO, liftIO)
import GHC.Conc (unsafeIOToSTM)
type Id = Integer
getOrCreateChannel :: (MonadIO m) => Id -> TVar (M.Map Id (Chan a)) -> m (Chan a)
getOrCreateChannel cid t = liftIO . atomically $ do
chans <- readTVar t
case M.lookup cid chans of
Just c -> return c
Nothing -> do
nchan <- unsafeIOToSTM newChan
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