[Haskell-cafe] synchronous channels in STM

Ryan Ingram ryani.spam at gmail.com
Thu Oct 9 12:36:19 EDT 2008

This seemed like an interesting problem, so I whipped together a
quick-and-dirty implementation of transactional CML semantics in
Haskell using STM.


main = do
   forkIO chsThread  -- administrative thread that manages communication

   forkIO (synchronize test1 >>= print)
   synchronize test2 >>= print

"synchronize" is like "atomically", except it organizes groups of
threads to do communication together before they can exit.  Inside of
synchronize, you have "readChan" and "writeChan" to communicate across
channels.  "newChan :: IO (Chan a)" creates a channel to communicate

You even have "retry" and "orElse"; they are called "mzero" and
"mplus", though :)

The code is guaranteed to find an interleaving of any currently
blocked processes that allows some subset of them to unblock, if there
is one.

Code is at http://ryani.freeshell.org/haskell/CHS.hs

Lots of obvious optimizations present themselves; for one thing, right
now, all the computation of the synchronizing threads takes place on
the administrative thread.  Also, the administrative thread attempts
to connect all combinations of blocked threads; only attempting to
communicate when a reader and writer meet on a particular channel
would be another clear improvement.

  -- ryan

More information about the Haskell-Cafe mailing list