Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon how can I use a WaitGroup with channels and mutexes in a Go program


how can I use a WaitGroup with channels and mutexes in a Go program


Here's an example of how you can use a `WaitGroup` along with channels and mutexes in a Go program:

go
package main

import (
    "fmt"
    "sync"
)

func main() {
    // Create a WaitGroup to wait for all goroutines to finish
    var wg sync.WaitGroup

    // Create a channel to communicate between goroutines
    ch := make(chan int, 10)

    // Create a mutex to protect a shared variable
    var mu sync.Mutex
    var sharedVar int

    // Launch 10 goroutines to read from the channel and update the shared variable
    for i := 0; i < 10; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            for x := range ch {
                mu.Lock()
                sharedVar += x
                mu.Unlock()
            }
        }()
    }

    // Send 100 values to the channel
    for i := 0; i < 100; i++ {
        ch <- i
    }
    close(ch)

    // Wait for all goroutines to finish
    wg.Wait()

    // Print the final value of the shared variable
    fmt.Println("Final value of shared variable:", sharedVar)
}

In this example, we have:

1. A `WaitGroup` to wait for all the goroutines to finish.
2. A channel `ch` to communicate between the main goroutine and the worker goroutines.
3. A mutex `mu` to protect the shared variable `sharedVar`.

The main goroutine launches 10 worker goroutines, each of which reads values from the channel `ch` and updates the shared variable `sharedVar` using the mutex `mu` to ensure mutual exclusion.

The main goroutine sends 100 values to the channel and then closes it. The worker goroutines continue to read from the channel until it is closed, at which point they exit.

Finally, the main goroutine waits for all the worker goroutines to finish using the `WaitGroup`, and then prints the final value of the shared variable.

This example demonstrates how you can use a combination of `WaitGroup`, channels, and mutexes to coordinate concurrent access to shared resources in a Go program.

Citations:
[1] https://www.devlane.com/blog/go-channels-waitgroups-mutexes
[2] https://dev.to/itnext/how-to-use-synchronization-primitives-in-go-mutex-waitgroup-once-1aee
[3] https://www.lucavall.in/blog/concurrency-in-go-goroutines-channels-mutexes-and-more
[4] https://stackoverflow.com/questions/36056615/what-is-the-advantage-of-sync-waitgroup-over-channels
[5] https://www.reddit.com/r/golang/comments/1b5s8n4/utility_of_go_channels/