golangRun multiple goroutines and wait for them to finish
package main
import "fmt"
import "sync"
func hi(idx int) {
  fmt.Println(idx)
}
func main() {
  var wg sync.WaitGroup
  
  for i := 1; i <= 3; i++ {
    i := i
    wg.Add(1)
    go func() {
      defer wg.Done()
      hi(i)
    }()
  }
  
  wg.Wait()
}ctrl + c| func main() {declare  | func hifunction that we will call in parallel | 
| wg sync.WaitGroupdeclare new wait group | i := iused not to mix  | 
| wg.Add(1)increase waiting counter on each iteration by  | defer wg.Done()call  | 
| wg.Wait()will wait for all goroutines to finish | |
Usage example
package main
import "fmt"
import "sync"
func hi(idx int) {
  fmt.Println(idx)
}
func main() {
  var wg sync.WaitGroup
  for i := 1; i <= 3; i++ {
    i := i
    wg.Add(1)
    go func() {
      defer wg.Done()
      hi(i)
    }()
  }
  wg.Wait()
}output
3
1
2
Related
More of Golang
- How to iterate over a slice in reverse order
- How to sleep for 500 milliseconds
- How to do regex replace
- How to make POST (form data) request using HTTP client
- How to use proxy with HTTP client
- How to set user agent for HTTP request
- How to sleep for 1 second
- Find the nameserver records of a domain name
- How to print new line with printf()
- How to get length of map
See more codes...