Advanced Go Concurrency Patterns [video]
blog.golang.org
blog.golang.org
The key thing shown in this talk to unlock all the other cool patterns is that a nil channel blocks indefinitely in a select statement, meaning it is never selected. So you can set channels to nil in order to "turn off" certain code paths in a select. Example:
var myChan chan int
if someCondition {
// Turn on case by setting the channel
myChan = someChannel
}
select {
case <-myChan:
// Do a thing. Will never execute if myChan is nil.
// ... etc.
} select {
case <-myChan:
// Do a thing
case <- time.After(10 * time.Second):
// default/error whatever
} for now := range time.NewTicker(time.Minute).C {
fmt.Printf("%s is the current time\n", now)
}
In case you are unfamiliar, the range keyword, when used on a channel, is equivalent to: for {
select {
case now := <-time.NewTicker(time.Minute).C:
fmt.Printf("%s is the current time\n", now)
}
} ticker := time.NewTicker(time.Minute)
for {
now, ok := <-ticker.C
if !ok {
break
}
fmt.Printf("%s is the current time\n", now)
}
Your two loops are superficially equivalent only because the ticker isn't going to close its channel. Plus, you're creating a new ticker on every iteration in your second example, and you don't need the select statement, because your only blocking on a single receive operation.The range over a channel is especially useful for a channel that will be closed, so you can break from the loop.
It's a lot like an object instance, responding to messages, changing internal state and emitting messages.
In fact, here is the same approach in SICP, where they start to model objects as messages passed to a closure with internal mutable state:
http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-21.html...
[scroll down a bit for exercise 3.11, the "cond dispatch" is analagous to the "for-select" case dispatch, except of course that golang select handles concurrency.]
It's the old "objects are a poor man's closures"/"closures are a poor man's object" duality.
Also, I love the tongue-in-cheek reference to what I presume is Google Reader:
Example: feed reader
My favorite feed reader disappeared. I need a new one.
Why not write one?
Where do we start?Python does have threadsafe queues in the standard library, which you can use to coordinate work between threads and processes.
C doesn't come with anything like this, but you can use a library like ZeroMQ. The main Go compilers are written in C, so clearly anything Go can do C can do too -- but it'll be more work.