6

[Golang] Wait For Goroutines to Finish

 3 years ago
source link: http://siongui.github.io/2015/03/23/go-wait-for-goroutine-to-finish/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Channel [1]

Wait for all goroutines to finish via channels:

Run Code on Go Playground

package main

import (
      "fmt"
)

func routine(site string, c chan int) {
      defer func() { c <- 1 }()

      // do something
      fmt.Println(site)
}

func main() {
      c := make(chan int)

      sites := []string{
              "https://www.google.com/",
              "https://duckduckgo.com/",
              "https://www.bing.com/"}

      for _, site := range sites {
              go routine(site, c)
      }

      // wait all goroutines to finish
      for i := 0; i < len(sites); i++ {
              <-c
      }
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK