goroutine

一些例子

等待 goroutine 完成

在线示例 - 等待 goroutine 完成

// main.go
package main

import (
	"fmt"
	"net/http"
	"sync"
)

func main() {
	fmt.Println("start...")
	var urls = []string{
		"https://www.baidu.com/",
		"https://www.cnblogs.com/",
		"https://www.oschina.net/",
	}

	var wg sync.WaitGroup
	for _, url := range urls {
		wg.Add(1)
		go fetch(&wg, url)
	}
	wg.Wait()
	fmt.Println("...end")
}

// fetch
func fetch(wg *sync.WaitGroup, url string) (string, error) {
	defer wg.Done()
	response, err := http.Get(url)
	if err != nil {
		return "", err
	}
	fmt.Println(fmt.Sprintf("request %s - response %s", url, response.Status))
	return response.Status, nil
}

// go run main.go

start...
request https://www.cnblogs.com/ - response 200 OK
request https://www.baidu.com/ - response 200 OK
request https://www.oschina.net/ - response 200 
...end

参考

posted @ 2019-06-12 10:40  taadis  阅读(120)  评论(0编辑  收藏  举报