Since I had to spend 10h in a train this weekend I was looking at some food for thought. For a long time I had a couple of slides about the Go language on my machine and so I started reading.
Go comes with a different concepts for synchronization. Channels are a construct baked into the language. They allow you to communicate between different go-routines etc. Basically I stopped reading after I came across the Channels section.
A channel allows you to send and receive data from it. Much like a Scala actor. By default a channel is performing blocking send and receive operations. Sounds pretty much like a blocking queue to me. The syntax is something like the following.
// Create a channel of int
var channel = make(chan int)
func send() {
// Send 1 to the channel.
// This operation blocks ...
channel <- 1
}
func receive() {
// Receive from channel
// This operation also blocks!
message := <- channel
fmt.Println(message) //1
}
go send()
go receive()
So ultimately I thought it should be quite easy to achieve something similar using Scala. I think this is an excellent example of the scalable part when it comes to Scala.
Go channels are diveded into reciver and sender channels, with a bidirectional channel type. The same can be achieved using Scala traits very easily. I could also add a couple of nice syntactic sugar like adding a foreach method to a channel which allows you to use it with Scala for comprehensions.
Have a look at this Gist for the complete source code. First of all one part is a little bit unfortunate. You are not able to define <- or <~ as a unary operator in Scala. So I thought I stick with the ! operator which you already know from actors and it is the analog to Go’s <-.
At the end of the file you will find a re-implementation of the Go Producer-Consumer example.
Something really cool is the fact that you can use Scala’s for-comprehensions which automatically exit once a channel is being closed. I think Go allows you do the same by specifying range when iterating over a channel. However I am not sure since I only had a brief look.
So is this useful? I do not know since I would probably stick with Scala actors for most of my multi-threading needs but it is still a great example of Scala’s flexibility as a language.