golang中协程同步sync.waitGroup

//使用golang中sync.WaitGroup来实现协程同步

package main

import (
	"fmt"
	"net/http"
	"io/ioutil"
	"time"
	"os"
	"sync"
)

var waitGroup = new(sync.WaitGroup)
func download(i int ){
		url := fmt.Sprintf("http://pic2016.ytqmx.com:82/2016/0919/41/%d.jpg", i)
		fmt.Printf("开始下载:%s\n", url)
		res,err := http.Get(url)
		if err != nil || res.StatusCode != 200{
			fmt.Printf("下载失败:%s", res.Request.URL)
		}
		fmt.Printf("开始读取文件内容,url=%s\n", url)
		data ,err2 := ioutil.ReadAll(res.Body)
		if err2 != nil {
			fmt.Printf("读取数据失败")
		}

		ioutil.WriteFile(fmt.Sprintf("pic2016/1_%d.jpg", i), data, 0644)
		//计数器-1
		waitGroup.Done()
}

func main()  {
	//创建多个协程,同时下载多个图片
	os.MkdirAll("pic2016", 0666)
	now := time.Now()

	for i :=1; i<24; i++ {
		//计数器+1
		waitGroup.Add(1)
		go download(i)
	}

	//等待所有协程操作完成
	waitGroup.Wait()
	fmt.Printf("下载总时间:%v\n", time.Now().Sub(now))
}

你可能感兴趣的:(go)