[Haskell-cafe] Spurious program crashes

Tomasz Zielonka tomasz.zielonka at gmail.com
Tue Nov 22 03:53:04 EST 2005


On Tue, Nov 22, 2005 at 08:30:33AM +0000, Joel Reymont wrote:
> I was under the impression that STM code needed to be in its own  
> monad. I was looking at Control.Concurrent.STM.TChan, for example,  
> where signatures like this exist:
> 
> newTChan :: STM (TChan a)	
> readTChan :: TChan a -> STM a	
> writeTChan :: TChan a -> a -> STM ()	

The STM monad is where synchronisation operations are grouped
in transactions. You can use STM as a drop-in replacement for
traditional Control.Concurrent synchronisation primitives by
simply wrapping every single operation in an "atomically" block:

    atomically :: STM a -> IO a

For example, a drop-in replacement for Chan:

    type Chan' a = TChan a

    newChan' = atomically newTChan
    readChan' c = atomically (readTChan c)
    writeChan' c v = atomically (writeChan c v)

the types of these functions are:

    newChan' :: IO (TChan a)
    readChan' :: TChan a -> IO a
    writeChan' :: TChan a -> a -> IO ()

But it is only grouping more operations in a transaction that will let
you benefit from the wonders of STM :-)

> I guess I should give this another look, re-read the STM paper and  
> check out your patch.

You definitely should do it. It is a very rewarding read.

> Regardless, simple is elegant and your Maybe solution is simple.

But it also requires that you restructure your code, doesn't it?
I am not sure we understood each other here.

One way to restructure your code to enable smooth transition to the
(Chan (Maybe String)) idea would be to change the type of "die request"
from (MVar ()) to (IO ()). You could use
    
    (dieVar, die) <- do
        dieVar <- newEmptyMVar
        return (dieVar, putMVar dieVar ())

where "dieVar" is used on the receiver side, and die is used on the
sender side. Then you could easily use a different notification
mechanism for logger:

    let die = writeChan parent Nothing

Best regards
Tomasz


More information about the Haskell-Cafe mailing list