Important Characteristics of Go: Concurrency Model

Let’s learn about the Go concurrency model.

Understanding the Go concurrency model

This lesson is a quick introduction to the Go concurrency model. The Go concurrency model is implemented using goroutines and channels. A goroutine is the smallest executable Go entity. In order to create a new goroutine, we have to use the go keyword followed by a predefined function or an anonymous function—both methods are equivalent as far as Go is concerned.

Note: We can only execute functions or anonymous functions as goroutines.

A channel in Go is a mechanism that, among other things, allows goroutines to communicate and exchange data. If you are an amateur programmer or you’re hearing about goroutines and channels for the first time, do not panic. Goroutines and channels, as well as pipelines and sharing data among goroutines, will be explained in much more detail later.

Although it is easy to create goroutines, there are other difficulties when dealing with concurrent programming, including goroutine synchronization and sharing data between goroutines—this is a Go mechanism for avoiding side effects when running goroutines. As main() runs as a goroutine as well, we do not want main() to finish before the other goroutines of the program because when main() exits, the entire program, along with any goroutines that have not finished yet will terminate. Although goroutines do not share any variables, they can share memory. The good thing is that there are various techniques for the main() function to wait for goroutines to exchange data through channels or, less frequently in Go, using shared memory.

Let's try our code

The following Go program, goRoutines.go, synchronizes goroutines using time.Sleep() calls. This is our first example, and there exist better ways to synchronize goroutines.

Get hands-on with 1200+ tech skills courses.