WaitGroup in Go

 WaitGroup in Go


The WaitGroup type is a synchronization mechanism provided by the sync package. A WaitGroup can be used to wait for a collection of goroutines to complete.


Here's an example of using a WaitGroup:



var wg sync.WaitGroup

for i := 0; i < 10; i++ {

    wg.Add(1)

    go func() {

        defer wg.Done()

        // do some work

    }()

}

wg.Wait()

fmt.Println("all goroutines completed")

In this example, we create a WaitGroup and add 10 goroutines to it. Each goroutine does some work and then calls the Done method on the WaitGroup. Finally, we call the Wait method on the WaitGroup to block until all goroutines have completed.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...