Behaviors of Channels
William Kennedy (speaker)
I learned over time that it’s best to forget about how channels are structured and focus on how they behave. So now when it comes to channels, I think about one thing: signaling. A channel allows one goroutine to signal another goroutine about a particular event. Signaling is at the core of everything you should be doing with channels. Thinking of channels as a signaling mechanism will allow you to write better code with well defined and more precise behavior.
Note: This post was live-blogged at dotGo 2017. Let us know on Twitter (@sourcegraph) if we missed anything. All content is from the talk; any mistakes or misrepresentations are our fault, not the speaker's.
Setup
Writing a service for a TV, but the tv stream fails because you can't write logs anymore. To simulate this we set up a custom io.Writer
to simulate problems that can happen called device
. So we use the log
package to log, but to our custom io.Writer
device
. When running the code the device
fails and the whole app fails because the calls to log.Println
are blocking.
Bill then proceeded to do live coding for a custom Logger which solves our problem, below is the code he wrote annotated with what he was explaining as he wrote it:
The important part above is the Drop Pattern implemented in Logger.Println
, since it will prevent the application being blocked due to device
blocking.