Go Gopher How to Go

sync.Mutex is used to protect shared data from being accessed by multiple goroutines at the same time. This is a fundamental concept in concurrent programming to prevent race conditions.

💡 Key Points

  • sync.Mutex provides mutual exclusion.
  • Use Lock() to acquire the lock and Unlock() to release it.
  • A common and robust pattern is to use defer mu.Unlock() to ensure the mutex is released.
  • The zero value for a sync.Mutex is an unlocked mutex.
  • Mutexes are used to guard critical sections of code where shared data is modified.

Using a Mutex

Here is an example of using a mutex to safely increment a counter from multiple goroutines.

package main

import (
	"fmt"
	"sync"
)

func main() {
	var mu sync.Mutex
	var counter int

	var wg sync.WaitGroup
	for i := 0; i < 1000; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			mu.Lock()
			counter++
			mu.Unlock()
		}()
	}
	wg.Wait()
	fmt.Println("Final counter:", counter)
}
Output:
Final counter: 1000

Mutex Operations

OperationSyntaxDescription
Declarevar mu sync.MutexDeclares a new mutex.
Lockmu.Lock()Acquires the lock, blocking if it's already held.
Unlockmu.Unlock()Releases the lock.
Defer Unlockdefer mu.Unlock()A common pattern to ensure the lock is released when the function returns.