Concurrency | Go

Blocking operation#

Normally in Go when we call a function doSomething() we wait for it to return (even if it has no value to return, we still wait for it to finish)

Goroutine#

An operation that does not block in Go will run in a separate process called a goroutine

Anonymous Functions#

Because the only way to start a goroutine is to put go in front of a function call, we often use anonymous functions when we want to start a goroutine.

Anonymous functions have a number of features which make them useful

  • They can be executed at the same time that the're declared - this is what the () at the end of the anonymous function is doing.
  • They maintain access to the lexical scope they are defined in - all the variables that are available at the point when you declare the anonymous function are also available in the body of the function.

Race Condition#

a bug that occurs when the output of our software is dependent on the timing and sequence of events that we have no control over.

Go can help us to spot race conditions with its built in [race detector][godoc_race_detector]. To enable this feature, run the tests with the race flag: go test -race.

Channels#

Channels are a Go data structure that can both receive and send values.

package concurrency
type WebsiteChecker func(string) bool
type result struct {
string
bool
}
func CheckWebsites(wc WebsiteChecker, urls []string) map[string]bool {
results := make(map[string]bool)
resultChannel := make(chan result)
for _, url := range urls {
go func(u string) {
// Send statement
resultChannel <- result{u, wc(u)}
}(url)
}
for i := 0; i < len(urls); i++ {
// Receive expression
r := <-resultChannel
results[r.string] = r.bool
}
return results
}

Always make channels#

Notice how we have to use make when creating a channel; rather than say var ch chan struct{}. When you use var the variable will be initialised with the "zero" value of the type. So for string it is "", int it is 0, etc.

For channels the zero value is nil and if you try and send to it with <- it will block forever because you cannot send to nil channels

You can see this in action in The Go Playground

Example#

func Racer(a, b string) (winner string) {
select {
case <-ping(a):
return a
case <-ping(b):
return b
}
case <-time.After(10 * time.Second):
return "", fmt.Errorf("timed out waiting for %s and %s", a, b)
}
}
func ping(url string) chan struct{} {
ch := make(chan struct{})
go func() {
http.Get(url)
close(ch)
}()
return ch
}

In our case, we don't care what type is sent to the channel, we just want to signal we are done and closing the channel works perfectly!

Why struct{} and not another type like a bool? Well, a chan struct{} is the smallest data type available from a memory perspective so we get no allocation versus a bool. Since we are closing and not sending anything on the chan, why allocate anything?

select#

We can wait for values to be sent to a channel with myVar := <-ch. This is a blocking call, as you're waiting for a value.

What select lets you do is wait on multiple channels. The first one to send a value "wins" and the code underneath the case is executed.

Timeouts#

time.After is a very handy function when using select. Although it didn't happen in our case you can potentially write code that blocks forever if the channels you're listening on never return a value. time.After returns a chan (like ping) and will send a signal down it after the amount of time you define.

Make it fast#

One formulation of an agile way of building software, often misattributed to Kent Beck, is:

Make it work, make it right, make it fast

Where 'work' is making the tests pass, 'right' is refactoring the code, and 'fast' is optimizing the code to make it, for example, run quickly. We can only 'make it fast' once we've made it work and made it right. We were lucky that the code we were given was already demonstrated to be working, and didn't need to be refactored. We should never try to 'make it fast' before the other two steps have been performed because

Premature optimization is the root of all evil -- Donald Knuth

Sync#

WaitGroup#

A WaitGroup waits for a collection of goroutines to finish. The main goroutine calls Add to set the number of goroutines to wait for. Then each of the goroutines runs and calls Done when finished. At the same time, Wait can be used to block until all goroutines have finished.

t.Run("it runs safely concurrently", func(t *testing.T) {
wantedCount := 1000
counter := Counter{}
var wg sync.WaitGroup
wg.Add(wantedCount)
for i := 0; i < wantedCount; i++ {
go func(w *sync.WaitGroup) {
counter.Inc()
w.Done()
}(&wg)
}
wg.Wait()
assertCounter(t, counter, wantedCount)
})

Mutex#

A Mutex is a mutual exclusion lock. The zero value for a Mutex is an unlocked mutex.

type Counter struct {
mu sync.Mutex
value int
}
func (c *Counter) Inc() {
c.mu.Lock()
defer c.mu.Unlock()
c.value++
}

A Mutex must not be copied after first use. So we should avoid passing a struct which has a mutex by value

When to use locks over channels and goroutines?#

The go wiki has a page dedicated to this topic; Mutex Or Channel

A common Go newbie mistake is to over-use channels and goroutines just because it's possible, and/or because it's fun. Don't be afraid to use a sync.Mutex if that fits your problem best.

Paraphrasing:

  • Use channels when passing ownership of data
  • Use mutexes for managing state

Don't use embedding because it's convenient#

type Counter struct {
// This is embedding
sync.Mutex
value int
}
  • Think about the effect embedding has on your public API.
  • Do you really want to expose these methods and have people coupling their own code to them?
  • With respect to mutexes, this could be potentially disastrous in very unpredictable and weird ways, imagine some nefarious code unlocking a mutex when it shouldn't be; this would cause some very strange bugs that will be hard to track down.