Mutexes and WaitGroups are synchronization mechanisms in Go that allow you to coordinate the execution of multiple goroutines. Here's an overview of how they work: 1. Mutexes: A mutex is a mutual exclusion lock that allows only one goroutine to access a shared resource at a time. In Go, mutexes are declared using the `sync` package and its `Mutex` type. For example:
var mutex sync.Mutex var count int func increment() { mutex.Lock() count++ mutex.Unlock() }
“
This code declares a mutex and a shared variable `count`. The `increment` function uses the mutex to lock the variable, increments it, and unlocks it to allow other goroutines to access it.
2. WaitGroups: A WaitGroup is a synchronization mechanism in Go that allows the main goroutine to wait for the completion of all the goroutines it has spawned. In Go, WaitGroups are declared using the `sync` package and its `WaitGroup` type. For example:
var wg sync.WaitGroup
for i := 0; i < 5; i++ { wg.Add(1) go func(i int) { defer wg.Done() fmt.Println("Goroutine", i) }(i) } wg.Wait()
`` This code creates a `WaitGroup` and spawns five goroutines thatprint their index. The `Add` method of the `WaitGroup` is used to increment the counter before each goroutine is spawned, and the `Done` method is used to decrement it after each goroutine finishes. The `Wait` method blocks until the counter reaches zero, indicating that all the goroutines have finished. 3. Combining Mutexes and WaitGroups: Mutexes and WaitGroups can be used together to coordinate the execution of multiple goroutines that access shared resources. For example:
var mutex sync.Mutex var wg sync.WaitGroup var count int func increment() { mutex.Lock() count++ mutex.Unlock() wg.Done() } for i := 0; i < 5; i++ { wg.Add(1) go increment() } wg.Wait() fmt.Println("Count:", count)
``
This code declares a mutex, a WaitGroup, and a shared variable `count`. The `increment` function uses the mutex to lock the variable, increments it, and unlocks it, and notifies the WaitGroup that it has finished. The main goroutine spawns five goroutines that call the `increment` function, waits for them to finish using the WaitGroup, and prints the final value of `count`.
Mutexes and WaitGroups are powerful synchronization mechanisms in Go that allow you to coordinate the execution of multiple goroutines and access shared resources safely. Byusing mutexes to protect shared resources and WaitGroups to wait for the completion of multiple goroutines, you can write concurrent programs that are safe, efficient, and scalable. By combining these mechanisms, you can create complex synchronization patterns that allow you to coordinate the execution of multiple tasks in an orderly and predictable way.