An Introduction to Goroutines

2 min read.

Goroutines, what are they exactly? According to the documentation they are a way to work with concurrency which basically means to execute functions at the same time.

They’re called goroutines because the existing terms—threads, coroutines, processes, and so on—convey inaccurate connotations. A goroutine has a simple model: it is a function executing concurrently with other goroutines in the same address space.

Unlike threads they are simpler to use and more memory efficent. For an in-depth comparison on goroutines and threads checkout this post.

Writing a goroutine

So for me, with a background in javascript, writing go routines is a lot like writing callback functions, yet different. The basic structure for creating a go routine is the following

go func() {
	//do stuff concurrently
}()

you can also execute named functions as go routines like this

func printAfterDelay(delay time.Duration) {
	time.Sleep(delay)
    fmt.Println("Delayed Message!")
}

go printAfterDelay(2000 * time.Millisecond)

//continue executing something else..

Communicating with goroutines

Go routines are great for computing things on the side without blocking the main flow. But sometimes you also might want to respond to a go routine finishing up.

This is where Channels comes into play. Using channels you can communicate between goroutines. When creating a Channel you need to specify what data type you want it to pass. If we want it to pass integears then we would create it like this

channel := make(chan int)

Now, we can use this channel to send integears between goroutines. Lets say we have one goroutine that makes calculations and then we have another that prints the results. The setup would look something like this

//setup goroutines
func add(a int, b int, out chan int) {
	c := a + b
	out <- c
}

func printer(in chan int) {
	for {
		result := <-in
		time.Sleep(2000 * time.Millisecond)
		fmt.Println(result)
	}
}

// setup chanel
c := make(chan int)

//init printer
go printer(c)

//add numbers
go add(5, 4, c)

// => 9

The example might seem a bit simple and you wouldn’t really use goroutines to add two numbers. However, goroutines might be useful for heavier calculations and other things that might take time, like writing to disk.

if you want to play around with the go routines youself you can find the code over on Github.

comments powered by Disqus