different ways to declare waitgroups in golang code example

Example 1: golang waitgroup

var wg sync.WaitGroup

for i := 1; i <= 5; i++ {
	wg.Add(1)
	go func(wg *sync.WaitGroup) {
		wg.Done()
	}()
}

wg.Wait()

Example 2: wait group golang

package main

	

import (
    "fmt"
    "sync"
    "time"
)

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

	

func main() {
    var wg sync.WaitGroup
    for i := 1; i <= 5; i++ {
        wg.Add(1)
        go worker(i, &wg)
    }
    wg.Wait()
}

Tags:

Go Example