golang中协程同步sync.waitGroup
2016-10-23 19:28
579 查看
//使用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)) }
相关文章推荐
- golang sync.WaitGroup解决goroutine同步
- golang sync WaitGroup
- golang sync WaitGroup
- golang sync WaitGroup
- GO: golang sync WaitGroup
- golang中的sync.WaitGroup
- golang waitgroup 及 sync.Once 示例
- Golang中的sync.WaitGroup用法实例
- golang sync WaitGroup
- golang--sync.WaitGroup使用示例
- golang sync WaitGroup
- golang sync.WaitGroup
- golang sync.WaitGroup解决goroutine同步
- Golang 1.7.3 Context 简单用法.类似sync.WaitGroup
- GOLANG sync.WaitGroup讲解
- golang-----golang sync.WaitGroup解决goroutine同步
- golang 的 sync.WaitGroup
- sync.WaitGroup的错误用法与纠正
- sync.WaitGroup的错误用法与纠正
- sync.WaitGroup的错误用法与纠正