Share & grow the world's code base!

Delve into a community where programmers unite to discover code snippets, exchange skills, and enhance their programming proficiency. With abundant resources and a supportive community, you'll find everything essential for your growth and success.

1 snippets
  • Example of WaitGroup in Go

    package main
    
    import (
    	"fmt"
    	"sync"
    	"time"
    )
    
    func main() {
    	wg := &sync.WaitGroup{} // WaitGroup is used to wait for the execution of all running goroutines
    
    	for i := 1; i <= 5; i++ {
    		wg.Add(1) // launch several goroutines and increment the counter in WaitGroup for each running goroutine
    
    		go func(id int) {
    			worker(id, wg)
    		}(i)
    	}
    
    	fmt.Println("waiting for all goroutines to complete")
    	wg.Wait() // block the execution of the program until the WaitGroup counter becomes equal to 0 again
    	fmt.Println("done")
    }
    
    func worker(id int, wg *sync.WaitGroup) {
    	fmt.Printf("worker %d started\n", id)
    	time.Sleep(time.Second) // Sleep simulates a long task
    	
        fmt.Printf("worker %d finished\n", id)
    	wg.Done() // notify WaitGroup that the worker has completed
    }
    
    // $ go run waitgroups.go 
    // waiting for all goroutines finished
    // worker 4 started
    // worker 1 started
    // worker 2 started
    // worker 3 started
    // worker 2 finished
    // worker 4 finished
    // worker 1 finished
    // worker 3 finished
    // done

    To wait for multiple goroutines to execute, you can use the built-in WaitGroup construct.