[Haskell-cafe] Bringing Erlang to Haskell

Sebastian Sylvan sebastian.sylvan at gmail.com
Mon Dec 12 19:28:22 EST 2005


On 12/12/05, Joel Reymont <joelr1 at gmail.com> wrote:
> Folks,
>
> I love the Erlang multi-processing experience and think that a lot of
> the mistakes that I made could be avoided. What I want to have is
>
> 1) Processes, aka threads with single-slot in/out mailboxes
> 2) A facility to keep a list of such processes and send events to
> them using their process id
> 3) A socket reader/writer abstraction that communicates with the
> outside world using using its mailboxes
>
> Probably some other things but I would start with the above. I also
> want to use STM for this.
>
> One particular thing that bugs me is that I cannot really use TChan
> for thread mailboxes. I don't think I experienced this problem with
> Erlang but using a TChan with a logger thread quickly overwhelms the
> logger and fills the TChan and a lot (hundreds? thousands) of other
> threads are logging to it. Someone said it's because the scheduler
> would give ther other threads proportionally more attention.

You could use a bounded TChan.
Chans are good because the smooth out "noise".. Ie a sudden surge of
messages can be handled without stalling the senders, but sustained
heavy traffic will cause a stall (preventing the TChan from growing
too big).

Here's an untested, off-the-top-of-my-head, implementation.. I may
have gotten some names wrong but it should be quite straightforward to
write a "real" implementation..

-- may want a newtype here?
type BoundedTChan a = (TVar Int, Int, TChan a) -- (current size, max, chan)

newBoundedTChan n = do sz <- newTVar 0
                                       ch <- newTChan
                                       return (sz,n,ch)

writeBoundedTChan (sz,mx,ch) x = do s <- readTVar sz
                                                        when (s >= mx) retry
                                                        writeTVar sz (s+1)
                                                        writeChan ch x

readBoundedTChan (sz,mx,ch)  = do modifyTVar sz (-1)
                                                      readTChan ch (s+1)



/S

--
Sebastian Sylvan
+46(0)736-818655
UIN: 44640862


More information about the Haskell-Cafe mailing list