4

Say I am simulating a network of some sort, and have a function which broadcasts a value over a list of Chans:

broadcast :: a -> [Receiver] -> IO ()
broadcast a = mapM_ (send a)

This will "send" the data to each Receiver in order. I would like instead to broadcast nondeterministically to all of the Receivers.

Thanks for any clues.

Don Stewart
  • 137,316
  • 36
  • 365
  • 468
jberryman
  • 16,334
  • 5
  • 42
  • 83

2 Answers2

3

How about just using GHC's concurrency?

broadcast :: a -> [Receiver] -> IO ()
broadcast a = mapM_ (forkIO . send a)

Then make sure to use the threaded RTS (compile with ghc -threaded).

Ganesh Sittampalam
  • 28,821
  • 4
  • 79
  • 98
  • 1
    That introduces some nondeterminism, sure, and for certain applications I can see it being the right way. But I'd suspect that the order in which messages are received, while nondeterministic, would generally stick pretty close to a linear ordering. If you want to ensure that things are mixed up, better to do so explicitly. – sclv May 10 '11 at 05:52
  • Perhaps also introduce a random delay after forking off each thread? Your solution makes sense for this restricted scenario, but I suspect that once you introduce any complications like communication, it won't generalise. – Ganesh Sittampalam May 10 '11 at 06:28
2

http://hackage.haskell.org/package/random-shuffle-0.0.2

broadcast a rs = do 
   g <- newStdGen
   mapM_ (send a) $ shuffle' rs (length rs) g
sclv
  • 38,665
  • 7
  • 99
  • 204