Mutexes
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.Mutexprovides mutual exclusion.- Use
Lock()to acquire the lock andUnlock()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.Mutexis 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)
}Final counter: 1000Mutex Operations
| Operation | Syntax | Description |
|---|---|---|
| Declare | var mu sync.Mutex | Declares a new mutex. |
| Lock | mu.Lock() | Acquires the lock, blocking if it's already held. |
| Unlock | mu.Unlock() | Releases the lock. |
| Defer Unlock | defer mu.Unlock() | A common pattern to ensure the lock is released when the function returns. |