WaitGroup in Go

Hits: 0

[]WaitGroup in [Go]

[The WaitGroup in the sync] package of the Go language can effectively solve the problem that the goroutine is not completed, and the main program is completed and the program ends.

There are only three methods of WaitGroup in the Go language standard library:

  1. Add(delta int) means adding a delta to the internal counter, where the parameter delta can be negative
  2. Done() means to reduce the value of the WaitGroup counter and should be executed at the end of the program. Equivalent to Add(-1)
  3. Wait() means to block until the WaitGroup counter is 0

Code example:

package main

import (
   "fmt"
   "sync"
)

func demo(index int) {
   for i := 1; i <= 5; i++ {
      fmt.Printf( "The %dth execution, the value of i is: %d\n" , index, i)
   }
   wg.Done()
}

var wg sync.WaitGroup

func main() {

   for i := 1; i <= 3; i++ {
      wg.Add(1)
      go demo(i)
   }
   fmt.Println ( "Start blocking" ) //Block until all tasks in the WaitGroup queue are automatically unblocked wg.Wait() fmt.Println ( " 
   Task execution ends 
   , unblocking" ) 
}

You may also like...

Leave a Reply

Your email address will not be published.