Skip to main content

A Week with Go, Day 5

Concurrent programming in Go makes use of coroutines, which are quaintly called "goroutines", and channels. Coroutines are functions executed asynchronously from the rest of your program, and channels are synchronous pipes through which the routines communicate. I had written a multi-threaded Kember Identity program in C a while back, and decided to rewrite it in Go to gain some exposure working with these features.

The Effective Go primer gives a hint of what goes on under the hood with coroutines in Go.
A goroutine has a simple model: it is a function executing in parallel with other goroutines in the same address space. It is lightweight, costing little more than the allocation of stack space. And the stacks start small, so they are cheap, and grow by allocating (and freeing) heap storage as required.

Goroutines are multiplexed onto multiple OS threads so if one should block, such as while waiting for I/O, others continue to run. Their design hides many of the complexities of thread creation and management.
Indeed, Go does a wonderful job of hiding the complexities of working with threads. Spawning the coroutine is as simple as prefacing the function call with go.
go kemberTest(start, tmp, ch)
Writing and reading values to and from a channel is done with <-. Both are blocking operations, so you don't have to worry about manually fumbling with locks to synchronize routines. The primer has this to say about channels:
Channels combine communication—the exchange of a value—with synchronization—guaranteeing that two calculations (goroutines) are in a known state.
if hash == curr {
    ch <- true
No muss, no fuss. Coroutines and channels work together to make concurrent programming a breeze! I sat down expecting to stumble through getting my threads to communicate properly, but to be honest I spent more time working out the correct type castings throughout the program than I spent on the concurrency piece.

The asynchronous nature of coroutines with the synchronous nature of channels make it easy to write generators, too.
func fib(ch chan int64) {
    var a, b int64 = 1, 2
    for {
        ch <- a
        a, b = b, a + b

func main() {
    ch := make(chan int64)
    go fib(ch)
    for i := <- ch; i > 0; i = <- ch {
After spending a week with Go I formed some good opinions and some bad opinions. The language has a dynamic feel with := and garbage collection which is nice, though I would have liked to have seen some more type inference being done by the compiler. An OO model that's not focused on hierarchical inheritance is a welcome change. Go is still rough around the edges and I wouldn't consider it ready to be a full-time development language for production projects just yet, but it has come quite a long way in the past year... and will undoubtedly continue to mature rapidly as an open source project.

Google did a disservice to Go when the language was first released by placing so much emphasis on compilation speed. The tech pundits and skeptics were right in questioning whether the world needed yet another language just because the current ones compiled too slow. Compilation is a function of the compiler after all, so if that was really the problem then a more appropriate solution would be to write a new compiler! But the pundits were ignorant in dismissing Go and believing there was no room for a new language. They failed to see an opportunity to re-examine old beliefs and explore now constructs. Many more would have taken Go seriously out of the gate if Google and early developers had touted its OO model and goroutines/channels instead of its compilation speed.

I can see myself using Go for a few side projects here and there, and perhaps larger projects in the future. Perhaps I'm just not comfortable yet with garbage collection in real-time and system-level programming yet, but I don't see it replacing my use of C; I choose C when a major need of my program is speed or memory and the unpredictable nature of a garbage collector works against those. But Go would definitely be a good choice for problems now solved using Java.

Thanks for spending the week with me (and Go); feel free to share your impressions of Go in the comments below. If you're interested, here's my Kember Identity code.


Popular posts from this blog

Geolocation Search

Services that allow users to identify nearby points of interest continue to grow in popularity. I'm sure we're all familiar with social websites that let you search for the profiles of people near a postal code, or mobile applications that use geolocation to identify Thai restaurants within walking distance. It's surprisingly simple to implement such functionality, and in this post I will discuss how to do so.

The first step is to obtain the latitude and longitude coordinates of any locations you want to make searchable. In the restaurant scenario, you'd want the latitude and longitude of each eatery. In the social website scenario, you'd want to obtain a list of postal codes with their centroid latitude and longitude.

In general, postal code-based geolocation is a bad idea; their boundaries rarely form simple polygons, the area they cover vary in size, and are subject to change based on the whims of the postal service. But many times we find ourselves stuck on a c…

Composing Music with PHP

I’m not an expert on probability theory, artificial intelligence, and machine learning. And even my Music 201 class from years ago has been long forgotten. But if you’ll indulge me for the next 10 minutes, I think you’ll find that even just a little knowledge can yield impressive results if creatively woven together. I’d like to share with you how to teach PHP to compose music. Here’s an example: You’re looking at a melody generated by PHP. It’s not the most memorable, but it’s not unpleasant either. And surprisingly, the code to generate such sequences is rather brief. So what’s going on? The script calculates a probability map of melodic intervals and applies a Markov process to generate a new sequence. In friendlier terms, musical data is analyzed by a script to learn which intervals make up pleasing melodies. It then creates a new composition by selecting pitches based on the possibilities it’s observed. . Standing on ShouldersComposition doesn’t happen in a vacuum. Bach was f…

Creepy JavaScript Tracking

I recently began allergy shots so my new Monday morning routine includes me sitting in a doctor's office for 30 minutes (I must wait after receiving the shots and be checked by a nurse to make sure there was no reaction). With nothing else better to do while I waited last week, I started playing around with some JavaScript. This is what I came up with:
<html> <head> <title>Test</title> <script type="text/javascript"> window.onload = function () { var mX = 0,  mY = 0, sX = 0,  sY = 0, queue = [], interval = 200, recIntv = null, playIntv = null, b = document.body, de = document.documentElement, cursor = document.getElementById("cursor"), record = document.getElementById("record"), play = document.getElementById("play"); window.onmousemove = function (e) { e = e || window.event; if (e.pageX || e.pageY) { …