Tuesday, May 26, 2015

Communicating Sequential Processes: Goroutines and Channels

This post, like Software Transactional Memory: Dining Philosophers, is motivated by the book Seven Concurrency Models in Seven Weeks. One of the concurrency models discussed is communicating sequential processes (CSP). Even though it was completely new to me, the idea has been around for several decades. I've wanted to check out Go for a while now and since it's a language whose design was influenced by CSP, it seems like a good time to write a Go program.

For concurrent programming, Go encourages shared values to be passed around on channels instead of by sharing memory. The value can only be accessed by one goroutine at a time. Unbuffered channels combine communication with synchronization, and buffered channels can be used like a semaphore. A goroutine is a function executing concurrently with other goroutines in the same address space. It's multiplexed onto multiple OS threads so a blocking goroutine doesn't hold up other goroutines.

In addition to the Seven Concurrency Models in Seven Weeks book, I think the Clojure core.async Channels blog sums up the motivation for channels well. Basically, they are an alternative to using queues to communicate between different components and to using events/callbacks. You avoid avoid thread overhead and callback hell.

I wrote a short program for a vending machine where money deposits and soda dispenses are values passed on channels. It was more difficult than expected to think this way, but the two goroutines only communicate over channels which was the intent.