CyberSpy

Rantings from a guy with way too much free time

Channel Your Inner Gopher

2017-12-13 Programming Rob Baruch

Channeling your Inner Gopher - (Literally) Reflecting upon Channels

Many gophers are likely familiar with the communication paradigm, channels. An elegant solution to communicate (uni or bidirectionally) typed information among go-routines. In it’s simplest form, we declare as type-valued channel variable, make it, and then send and receive data through it. Easy enough!

package main

import (
        "fmt"
)

func main() {
        var simpleChan chan int = make(chan int)

        go func(c chan int) {
                // send important data to the channel
                c <- 42
                close(c)
        }(simpleChan)

        // receive data
        num := <-simpleChan
        fmt.Printf("got %d\n", num)

}

In our trivial example above, we create an chan int typed-channel and initialize it using make.

Continue reading

Gogo

Here we gogo!

Years ago, I wrote an interesting article that I thought might be worth re-posting (and revising) here on my blog. For a while I got into programming in golang and in the early going (pun-alert!), there were a lot of idioms that were not well understood by a noob. One of those paradigms was channels, go-routines, and signals used simultaneously. Taken separately, they are more easily understood. But when taken together, there can be some confusion. In this article, I address how to properly establish a signal-handler and a channel to terminate go-routines when the user interrupts the program with a signal such as ctrl-c or kill(1).

Continue reading