chapter nine

9 Concurrency

 

This chapter covers

  • Go’s concurrency model
  • Using internal libraries to manage concurrent tasks
  • Creating channels for asynchronous communication
  • Applying concurrent patterns

Imagine you have a list of chores: bake a chicken, do the laundry, and send an email. You might work on all three at once. While the chicken bakes and the laundry runs, you can send your email. In this scenario, multiple tasks are happening concurrently. When two or more tasks are being executed at the same time, such as the oven and washing machine running simultaneously, that’s called parallelism.

It’s common to confuse concurrency and parallelism. Concurrency is about managing multiple tasks at once, allowing progress on several activities by switching between them. Parallelism is about actually performing multiple tasks at the same time, typically on separate processors or cores.

Modern applications rely on concurrency to remain responsive, such as when you receive a call while browsing the web or sending an email. Without concurrency, programs would have to finish one task before starting another, making them slow and unresponsive.

9.1 When to use concurrency

9.2 Sync package

9.2.1 Wait groups

9.2.2 Error Groups

9.2.3 Mutexes

9.3 Adding some context

9.4 Channels

9.5 Concurrency patterns

9.5.1 Workers

9.5.2 Fan-out and fan-in

9.6 Helpful concurrency tips

9.6.1 Best practices for Go concurrency

9.6.2 When to use concurrency in Go

9.6.3 When not to use concurrency in Go

Summary