Concurrency Basics: Doing Things Simultaneously
7 min read
Welcome to the exciting world of Go's concurrency! This is one of the most powerful features of the language, allowing you to write programs that can handle multiple tasks at once, making them faster and more efficient. Don't worry, we'll start with the basics and build up from there.
1. Concurrency vs. Parallelism in Go
Before we dive into the cool stuff, let's get some definitions straight. People often use "concurrency" and "parallelism" interchangeably, but they're actually different concepts.
The Problem: Imagine you're making a big breakfast. You need to make toast, fry some eggs, and brew a pot of coffee. If you do these tasks one after another (sequentially), it's going to take a long time. Your toast will be cold by the time the coffee is ready! This is inefficient.
The Solution: You could work on all these tasks around the same time. You start the coffee maker, put the bread in the toaster, and then start frying the eggs. You're managing multiple tasks at once, even if you're only actively doing one thing at any given moment. This is concurrency.
What about Parallelism? Now, imagine you have a friend helping you in the kitchen. You're frying the eggs while your friend is making the toast. You are both working on different tasks at the exact same time. This is parallelism. Parallelism is about doing lots of things at once.
How Go Handles It:
Go is designed for concurrency. It provides tools to structure your program to handle multiple tasks at the same time. If you have a computer with multiple processor cores, Go's runtime can automatically run your concurrent tasks in parallel, without you having to do anything special!
In short:
- Concurrency is about dealing with lots of things at once. It's a way of structuring your program.
- Parallelism is about doing lots of things at once. It's the simultaneous execution of tasks and requires multiple processors.
An interesting fact: Rob Pike, one of the creators of Go, famously said, "Concurrency is not parallelism." This distinction is a core philosophy of the Go language.
2. Goroutines: Lightweight Threads 🏃♀️
The Problem: In many programming languages, if you want to do things concurrently, you have to create "threads." Threads are like separate workers that can perform tasks. However, traditional operating system threads can be slow to create and consume a lot of memory. Creating thousands of them can really slow down your application.
The Solution: Goroutines!
Go has its own lightweight version of threads called goroutines. They are managed by the Go runtime, not the operating system directly, which makes them incredibly cheap and fast to create. You can easily have thousands, or even hundreds of thousands, of goroutines running in a single program without breaking a sweat.
Creating a Goroutine:
Starting a goroutine is incredibly simple. You just use the go keyword before a function call.
package main
import (
"fmt"
"time"
)
func sayHello() {
fmt.Println("Hello from the goroutine!")
}
func main() {
go sayHello() // This starts a new goroutine
fmt.Println("Hello from the main function!")
time.Sleep(1 * time.Second) // We'll explain this later
}When you run this code, you might see the output in a different order each time! That's because the sayHello function is running concurrently with the main function.
Under the Hood: Go uses a concept called an M:N scheduler, which means it maps M goroutines onto N operating system threads. This is what makes goroutines so efficient. The Go runtime handles all the complex details of scheduling for you.
3. Synchronizing Execution with sync.WaitGroup 🤝
The Problem: In the previous example, we used time.Sleep(1 * time.Second) to make the main function wait. Why? The main function itself runs in a goroutine. If the main goroutine finishes before other goroutines you've started, the entire program will exit, and those other goroutines might not get a chance to finish their work. Using time.Sleep is a hacky and unreliable way to wait. What if your goroutine takes longer than one second to run?
The Solution: sync.WaitGroup
A WaitGroup is a way to wait for a collection of goroutines to finish. It's like a counter. You tell the WaitGroup how many goroutines you're starting, and then each goroutine tells the WaitGroup when it's done. The main function can then wait for the counter to go back to zero.
A WaitGroup has three main methods:
Add(int): This increases theWaitGroupcounter by the given number. You usually call this before starting a goroutine.Done(): This decreases the counter by one. A goroutine calls this when it's finished.Wait(): This blocks the execution of the function it's in until theWaitGroupcounter is zero.
Example:
package main
import (
"fmt"
"sync"
"time"
)
func worker(id int, wg *sync.WaitGroup) {
defer wg.Done() // This will be called when the function exits
fmt.Printf("Worker %d starting\n", id)
time.Sleep(time.Second) // Simulate some work
fmt.Printf("Worker %d done\n", id)
}
func main() {
var wg sync.WaitGroup // Create a new WaitGroup
for i := 1; i <= 3; i++ {
wg.Add(1) // Increment the counter before starting the goroutine
go worker(i, &wg)
}
wg.Wait() // Wait for all workers to finish
fmt.Println("All workers have finished!")
}In this example, the main function will wait until all three worker goroutines have called wg.Done(). This is a much more robust and reliable way to synchronize goroutines.
Industry Practice: It's a common and good practice to call defer wg.Done() at the beginning of your goroutine's function. This ensures that Done() is called even if your function has an error and panics.
4. Understanding and Detecting Race Conditions 🏁
The Problem: When you have multiple goroutines accessing and modifying the same piece of data at the same time, you can run into a "race condition." The final value of the data depends on the unpredictable order in which the goroutines execute. This can lead to bugs that are very hard to track down because they might only happen sometimes.
Imagine two people trying to update the same number on a whiteboard at the same time. One wants to add 5, and the other wants to multiply by 2. The final result will be different depending on who gets to the whiteboard first.
Detecting Race Conditions with Go's Race Detector:
Go has a built-in tool to help you find race conditions. You can use the -race flag when you run or test your code.
Example of a Race Condition:
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
var counter int
for i := 0; i < 1000; i++ {
wg.Add(1)
go func() {
defer wg.Done()
counter++ // Potential race condition!
}()
}
wg.Wait()
fmt.Println("Final counter:", counter)
}If you run this program, you might get a different counter value each time, and it will likely be less than 1000. This is because multiple goroutines are trying to read and write to counter simultaneously.
Now, let's use the race detector:go run -race your_program_name.go
The race detector will print a report if it finds a data race, telling you where in your code the conflicting memory access is happening.
Funny exaggeration: A race condition is like two squirrels trying to bury a nut in the same spot. They'll just keep digging up each other's nut, and in the end, no one is happy, and the nut is probably gone.
We'll cover how to fix race conditions with tools like mutexes and channels in a later guide. For now, knowing how to detect them is a huge step forward!
References for Extra Reading:
- Concurrency vs. Parallelism: https://bytebytego.com/blog/concurrency-vs-parallelism
- A Deeper Dive into Goroutines: https://www.geeksforgeeks.org/goroutines-concurrency-in-golang/
- Go by Example: WaitGroups: https://gobyexample.com/waitgroups
- The Go Race Detector: https://go.dev/doc/articles/race_detector
Challenge
Challenge: Concurrent Job Processor
Your task is to write a Go program that simulates processing a batch of jobs concurrently using goroutines and ensures the main program waits for all jobs to complete before exiting.
Requirements:
- Define a function named
processJobthat accepts three arguments: an integeridfor the job, a pointer to async.WaitGroup, and a pointer to a shared integer variable that will act as a counter for completed jobs. - Inside the
processJobfunction, you must:- Use
deferto signal to theWaitGroupthat the goroutine is done. - Print a message indicating which job ID is starting (e.g.,
Processing job 1). - Simulate work by pausing the execution for
50 * time.Millisecond. - Increment the shared counter.
- Use
- In the
mainfunction:- Initialize a
sync.WaitGroupand a shared integer counter set to0. - Define a constant or variable
numJobswith a value of8. - Write a loop that launches
numJobsgoroutines, each executing theprocessJobfunction. - You must call
Add()on the WaitGroup for each goroutine you are about to start. - The
mainfunction must block and wait until allprocessJobgoroutines have completed. - After all jobs are finished, print the final value of the shared counter in the format:
All jobs completed. Total processed: X, whereXis the final counter value.
- Initialize a
Expected result
Your code should correctly implement a concurrent pattern using goroutines and a sync.WaitGroup for synchronization.
A correct solution will have:
- A
processJobfunction with the signaturefunc processJob(id int, wg *sync.WaitGroup, counter *int). - A
defer wg.Done()statement as the first line insideprocessJob. - The
mainfunction initializingvar wg sync.WaitGroupandvar counter int. - A loop that runs 8 times. Inside the loop,
wg.Add(1)is called, followed by a call togo processJob(...). - A
wg.Wait()call after the loop inmainto block execution. - A final
fmt.Printfstatement to display the value of the counter.
Note: Incrementing the shared counter from multiple goroutines without a mutex creates a race condition. While the primary goal is to correctly use WaitGroup, recognizing this potential issue is a key part of the exercise.