Sync Package (Mutex/WaitGroup)Advanced
1Question 1 of 1
goHow do sync.Mutex and sync.WaitGroup synchronize concurrent execution in Go?
Explanation & Concept
• `sync.WaitGroup`: Waits for a collection of goroutines to finish. You increment with `Add()`, decrement inside goroutines with `Done()`, and block with `Wait()`. • `sync.Mutex`: Provides mutual exclusion locks to prevent concurrent race conditions on shared memory.
Code Example
go
package main
import (
"fmt"
"sync"
)
type SafeCounter struct {
mu sync.Mutex
count int
}
func (c *SafeCounter) Increment(wg *sync.WaitGroup) {
defer wg.Done()
c.mu.Lock()
defer c.mu.Unlock()
c.count++
}
func main() {
var wg sync.WaitGroup
counter := SafeCounter{}
for i := 0; i < 100; i++ {
wg.Add(1)
go counter.Increment(&wg)
}
wg.Wait()
fmt.Println("Final count:", counter.count) // Guaranteed 100
}How It Works & Key Takeaways
`sync.Mutex` ensures that only one goroutine increments `count` at a time, preventing race condition data corruption.
Mock Test · 1 Questions · Optional
Ready for Testing in Go?
Take a quick test to evaluate yourself, or move straight to the next module.
Advanced1 questions