[Haskell-cafe] Observer pattern in Haskell?
nccb2 at kent.ac.uk
Mon Nov 9 12:41:32 EST 2009
Andy Gimblett wrote:
>>> was a bit surprised at first that the observers were called
>>> synchronously. Asynchronous is what I'd expect, and it's also
>>> harder to code the asynchronous handlers wrongly. One blocking call
>>> (such as putMVar) in a synchronous handler can screw up your whole
>>> program by delaying the subsequent observers (and at that stage, the
>>> order in which the observers were added begins to matter).
> True, but the observers shouldn't be able to access the MVars
> directly, I think? They should only be able to use the exposed
> interface, which won't let that happen?
Just to clarify -- I meant access to another MVar. Basically, if I do this:
do v <- newMVar
addObserver sub (putMVar v)
If when the observers are run, the MVar v (that I've allocated) is
non-empty, my code will block until it is empty, which will also block
all the subsequent observers from being run (and block the code that
called setValue) until the MVar is cleared by another thread. So my one
poorly-written observer could deadlock (or cause stutter in) the system,
whereas in the forkIO version, this observer would be fine -- it would
block in its own new thread.
More information about the Haskell-Cafe