WaitGroup and Mutex in Golang (Keeping Goroutines in Check!)

Concurrency in Go is awesome, but with great power comes great chaos!  That’s where WaitGroup and Mutex come in—to keep your Goroutines disciplined and your data safe! 

What is WaitGroup? (Goroutine Roll Call!)

WaitGroup is like a teacher taking attendance—it waits for all Goroutines to finish before moving on. No one gets left behind! 

Basic Syntax:

var wg sync.WaitGroup
  • wg.Add(n) → Tells Go that n Goroutines are running.
  • wg.Done() → Called when a Goroutine finishes.
  • wg.Wait() → Blocks until all Goroutines are done.

Example: Using WaitGroup

package main
import (
    "fmt"
    "sync"
    "time"
)

func worker(id int, wg *sync.WaitGroup) {
    defer wg.Done() // Mark this Goroutine as finished
    fmt.Printf("Worker %d starting\n", id)
    time.Sleep(2 * time.Second)
    fmt.Printf("Worker %d done\n", id)
}

func main() {
    var wg sync.WaitGroup
    for i := 1; i <= 3; i++ {
        wg.Add(1) // Add Goroutine to WaitGroup
        go worker(i, &wg)
    }
    wg.Wait() // Wait for all Goroutines to finish
    fmt.Println("All workers completed!")
}

Without WaitGroup.Wait(), the program would exit before the Goroutines complete. Patience is key! 

What is Mutex? (The Data Bodyguard!)

A Mutex (mutual exclusion) ensures only one Goroutine accesses critical data at a time. It’s like a toilet with a lock—only one person can use it at a time! 

Basic Syntax:

var mu sync.Mutex
  • mu.Lock() → Locks the resource.
  • mu.Unlock() → Unlocks it .

Example: Using Mutex to Prevent Data Race

package main
import (
    "fmt"
    "sync"
    "time"
)

var counter int
var mu sync.Mutex

func increment(wg *sync.WaitGroup) {
    defer wg.Done()
    mu.Lock()   // Lock before modifying `counter`
    counter++   // Critical section 
    mu.Unlock() // Unlock after modification
}

func main() {
    var wg sync.WaitGroup
    for i := 0; i < 5; i++ {
        wg.Add(1)
        go increment(&wg)
    }
    wg.Wait()
    fmt.Println("Final Counter Value:", counter)
}

Without Mutex, multiple Goroutines might modify counter at the same time, leading to unpredictable results.

When to Use WaitGroup vs Mutex

Feature WaitGroup Mutex
Purpose Waits for Goroutines to finish Prevents data race
Blocks Execution? Yes, until all Goroutines are done Yes, only when locking
Works With Any Goroutines Shared resources
Analogy A teacher checking attendance  A toilet lock 

Use WaitGroup when waiting for Goroutines to complete. Use Mutex when protecting shared resources.

Concurrency in Go without WaitGroup & Mutex is like a rock concert without security—total madness! These tools ensure your Goroutines behave and your data stays intact. 

Post a Comment

0 Comments