[Haskell-cafe] Broadcast signals between threads
Joachim Breitner
mail at joachim-breitner.de
Fri May 25 13:57:45 EDT 2007
[Arg. Just lost the mail and have to re-type it. Sorry if I’m not as
verbose as I should be].
Hi,
I’m writing a TCP server app ATM. It has one thread per client. Some of
the clients want to be notified if the internal state changes, while
others are happily chatting with the server, possible modifying the
internal state. What I need now is a way for the chatting thread to
signal “anyone interested” that the state has changed.
The semantics should be roughly these:
* All listening threads run some wait-for-signal command that blocks
until the signal is sent.
* The state changing thread notifies the others by some
signal-sending-command, which should not block.
* It does not matter if no one is listening, or if threads miss signals
because they are doing something else for the moment, or if several sent
signals are handled only once.
Here is my implementation so far:
newtype MSignal a = MS (MVar a)
newMSignal = MS `liftM` newEmptyMVar
sendMSignal (MS mv) v = do
forkIO $ takeMVar mv >> return () -- Cleanup afterwards
putMVar mv v
receiveMSignal (MS mv) = readMVar mv
It builds on MVar’s promise that takeMVar and readMVar commands are
handled FIFO, so by spawning a takeMVar thread, the sender ensures that
exactly after all currently waiting threads are served the value is
taken out of the MVar and everything is done. readMVar will both take
the value and put it back, so that the next waiting thread (or the
sending thread’s cleanup thread) can take the value.
Do you think this is a sensible way to do it? Any pitfalls that I have
overlooked? Might this be useful enough to be included in some
mainstream library?
Greetings,
Joachim
--
Joachim Breitner
e-Mail: mail at joachim-breitner.de
Homepage: http://www.joachim-breitner.de
ICQ#: 74513189
More information about the Haskell-Cafe
mailing list