Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Mutexes: Locking for Safety | Synchronization and Best Practices
/
Concurrency in Go

bookMutexes: Locking for Safety

Desliza para mostrar el menú

Mutexes: Locking for Safety

When you write concurrent programs in Go, you often need to protect shared data from being changed by multiple goroutines at the same time. If two or more goroutines try to update the same variable without coordination, your program can behave unpredictably. This is called a "race condition."

A mutex (short for "mutual exclusion") is a tool that helps you prevent race conditions. It lets only one goroutine access a critical section of code at a time. Think of a mutex like a lock on a door: only one person can enter the room when the door is locked, and others must wait their turn.

In this chapter, you will learn:

  • What a mutex is and why it is important in concurrent Go programs;
  • How to use the sync.Mutex type to lock and unlock critical sections;
  • Common mistakes to avoid when working with mutexes;
  • Best practices for writing safe, efficient concurrent code.

By the end, you will be able to use mutexes to keep your Go programs safe and reliable when multiple goroutines interact with shared data.

What Is a Mutex?

A mutex (short for "mutual exclusion") is a synchronization tool that helps you control access to shared resources in your Go programs. When multiple goroutines try to read and write the same data at the same time, you can run into race conditions—unexpected bugs caused by unsynchronized access. A mutex ensures that only one goroutine can access a critical section of code or data at a time.

How Mutexes Prevent Race Conditions

When you use a mutex, you "lock" it before accessing shared data and "unlock" it after you are done. This guarantees that only one goroutine can enter the critical section at any given moment. If another goroutine tries to lock the mutex while it is already locked, it will wait until the mutex becomes available.

Key points about mutexes:

  • Mutexes help you avoid race conditions by making sure only one goroutine can access certain code or data at a time;
  • You lock a mutex before entering a critical section, and unlock it after you finish;
  • If a mutex is already locked, other goroutines will wait until it is unlocked;
  • Forgetting to unlock a mutex can cause your program to freeze (deadlock).

In Go, you use the sync.Mutex type from the standard library to create and manage mutexes. You will see how this works in practice in upcoming examples.

When to Use Mutexes in Go

Mutexes help you manage access to shared data when multiple goroutines are running at the same time. Use a mutex when you need to:

  • Protect a variable or data structure from being changed by more than one goroutine at once;
  • Prevent race conditions, where two or more goroutines try to read and write to the same data at the same time;
  • Ensure that only one goroutine can enter a critical section of code that updates shared state;
  • Coordinate updates to resources like counters, maps, or slices that are shared between goroutines.

If your program has several goroutines that only read shared data, you may not need a mutex. But as soon as any goroutine needs to write or update shared data, use a mutex to lock and unlock that part of your code. This keeps your program safe and avoids unexpected bugs.

main.go

main.go

copy
1234567891011121314151617181920212223242526272829303132
package main import ( "fmt" "sync" ) func main() { var ( counter int mutex sync.Mutex wg sync.WaitGroup ) // Start 3 goroutines that increment the counter for i := 1; i <= 3; i++ { wg.Add(1) go func(id int) { defer wg.Done() // Lock the mutex before accessing shared data mutex.Lock() fmt.Printf("Goroutine %d incrementing counter\n", id) counter++ // Unlock the mutex after updating shared data mutex.Unlock() }(i) } wg.Wait() fmt.Printf("Final counter value: %d\n", counter) }
question mark

Which Go synchronization primitive is specifically designed to prevent multiple goroutines from accessing shared data at the same time?

Select the correct answer

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 3. Capítulo 2

Pregunte a AI

expand

Pregunte a AI

ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

Sección 3. Capítulo 2
some-alt