Sobes.tech
Junior — Middle

Can you show an example of using the group wait mechanism in programming?

sobes.tech AI

Answer from AI

In Go, the synchronization mechanism WaitGroup is used to wait for a set of goroutines to finish. It is convenient when you need to launch several parallel tasks and wait for their completion.

Example:

package main

import (
    "fmt"
    "sync"
)

func worker(id int, wg *sync.WaitGroup) {
    defer wg.Done() // Indicate that the work is done
    fmt.Printf("Worker %d started\n", id)
    // Here can be any work
    fmt.Printf("Worker %d finished\n", id)
}

func main() {
    var wg sync.WaitGroup
    numWorkers := 3

    wg.Add(numWorkers) // Set the number of goroutines to wait for

    for i := 1; i <= numWorkers; i++ {
        go worker(i, &wg)
    }

    wg.Wait() // Wait until all goroutines call Done()
    fmt.Println("All workers completed")
}

In this example, main launches 3 goroutines, each executing the worker function. WaitGroup allows main to wait for all goroutines to finish before exiting the program.