[Shootout-list] Haskell ring of messages - fair?

Einar Karttunen ekarttun@cs.helsinki.fi
Thu, 23 Sep 2004 08:44:12 +0300


This is a MIME-formatted message.  If you see this text it means that your
E-mail software does not support MIME-formatted messages.

--=_courier-336-1095918256-0001-2
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit
Content-Disposition: inline

Hello

Is the attached solution fair?
It uses mvars (a kind of synchronized variables) 
to pass the messages and clears the test in
3-4 secs. Using channels is much slower...

ps. of course it may contain bugs..

- Einar Karttunen

--=_courier-336-1095918256-0001-2
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="Ring2.hs"

module Main where

import Control.Concurrent
import System(getArgs)

main = getArgs >>= \[np,nmsg] -> ring (read np) (read nmsg) >>= print

ring n nmsg = do first <- newEmptyMVar
		 master<- newEmptyMVar
		 forkIO (initRing n first master)
		 sendRing nmsg first master 0

initRing 0 prev master = loop prev master
initRing n prev master = do c <- newEmptyMVar
			    forkIO (initRing (n-1) c master)
			    loop prev c

loop prev next = takeMVar prev >>= putMVar next >> loop prev next

sendRing 0 _ _ i = return i
sendRing n f m i = putMVar f i >> takeMVar m >> sendRing (n-1) f m (i+1)


--=_courier-336-1095918256-0001-2--