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 {
    fmt.Println(hash)
    ch <- true
    return
}
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 {
        fmt.Println(i)
    }
}
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.

Comments

Popular posts from this blog

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 Shoulders Composition doesn’t happen in a vacuum. Bach wa

Learning Prolog

I'm not quite sure exactly I was searching for, but somehow I serendipitously stumbled upon the site learnprolognow.org a few months ago. It's the home for an introductory Prolog programming course. Logic programming offers an interesting way to think about your problems; I've been doing so much procedural and object-oriented programming in the past decade that it really took effort to think at a higher level! I found the most interesting features to be definite clause grammars (DCG), and unification. Difference lists are very powerful and Prolog's DCG syntax makes it easy to work with them. Specifying a grammar such as: s(s(NP,VP)) --> np(NP,X,Y,subject), vp(VP,X,Y). np(np(DET,NBAR,PP),X,Y,_) --> det(DET,X), nbar(NBAR,X,Y), pp(PP). np(np(DET,NBAR),X,Y,_) --> det(DET,X), nbar(NBAR,X,Y). np(np(PRO),X,Y,Z) --> pro(PRO,X,Y,Z). vp(vp(V),X,Y) --> v(V,X,Y). vp(vp(V,NP),X,Y) --> v(V,X,Y), np(NP,_,_,object). nbar(nbar(JP),X,3) --> jp(JP,X). pp(pp(PREP,N

What's Wrong with OOP

Proponents of Object Oriented Programming feel the paradigm yields code that is better organized, easier to understand and maintain, and reusable. They view procedural programming code as unwieldy spaghetti and embrace OO-centric design patterns as the "right way" to do things. They argue objects are easier to grasp because they model how we view the world. If the popularity of languages like Java and C# is any indication, they may be right. But after almost 20 years of OOP in the mainstream, there's still a large portion of programmers who resist it. If objects truly model the way people think of things in the real world, then why do people have a hard time understanding and working in OOP? I suspect the problem might be the focus on objects instead of actions. If I may quote from Steve Yegge's Execution in the Kingdom of Nouns : Verbs in Javaland are responsible for all the work, but as they are held in contempt by all, no Verb is ever permitted to wander about