Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go Channels in Ruby

In the Go programming language, you can send Messages around using a construct called "Channels". http://golang.org/doc/effective_go.html#channels

I would love to use something like that in Ruby, especially for IPC.

Pseudocode of what I want:

channel = Channel.new

fork do
  3.times{ channel.send("foo ") }
  exit!
end

Thread.new do
  3.times{ channel.send("bar ") }
end

loop do
  print channel.recv
end

# ~> bar foo foo bar bar foo

Is there any construct, library or equivalent for Ruby which works like that ?

If not: What is the best way to build such an abstraction?

UPDATE: To clarify what I need from these Channels.

One use case: Some forked workers waiting for jobs. They all read from the same JobChannel and report results to the same ResultChannel.

The Channels I need

  • are very fast,
  • writes do not block, (message sending)
  • reads do block, (message receiving)
  • do not need special treatment before forking,
  • lightweight and simple would be nice.

So far I played around with

  • DRb, (opposite of lightweight + slow + too much magic for my little brain)
  • Sockets, (UNIXSocket, TCPSocket ... Sockets seem to have many many ways of using them. I got a half-working channel on UNIXSockets. If you think sockets make sense, what subset of features should I look at?)
  • Pipes. (Connecting more than 2 Processes seems to be non-trivial)

If any of those was already the perfect technology for my problem, please provide tutorials etc. which have more focused information on my requirements.

like image 988
Julius Eckert Avatar asked Jun 17 '10 13:06

Julius Eckert


1 Answers

Go's idea of message passing via channels, as a first-class construct, really only makes sense in the presence of concurrency (goroutines, tasklets, whatever you'd care to call them). With cheap concurrency, blocking a tasklet or coroutine is no longer a problem, and blocking message passing starts to make a lot more sense.

If this were Python, I'd point you at Stackless; in Ruby, perhaps Revactor or NeverBlock fit the bill for you?

like image 171
esm Avatar answered Sep 26 '22 00:09

esm