Concurrency in Go

Go is well-known and loved for its concurrency. The go runtime manages lightweight threads called goroutines. Goroutines are quick and simple to write.

You just type go before the function you want to execute asynchronously, in another thread.

Sounds easy enough?

Goroutines are Go’s way of writing asynchronous code.

It’s important to understand how a goroutine, and concurrency more generally, works. Go provides ways to manage goroutines and make them more manageable and predictable in a complex program.

1) Don’t make assumptions about execution order during asynchronous routines

When scheduling concurrent tasks in Go, it is important to remember the unpredictability of asynchronous tasks.

Blending asynchronous with synchronous computation can be done, but as long as the synchronous task doesn’t make any assumptions about asynchronous tasks.

It is a common mistake for beginners to create a goroutine, then carry on with a synchronized task that depends on the result of that goroutine. For example, if that goroutine was to write to a variable outside of its’ scope, which is then used during the synchronized task.

#golang #go #programming

How to Write Bug-Free Goroutines in Go (Golang)
11.25 GEEK