go 使用信号量判断多个协程处理完毕

package main

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

var urls = []string{
   "http://www.baidu.com/",
   "http://www.clearloveuzi.cn/",
   "http://www.sina.com/",
}

把上面那个给换了种方式判断协程处理完(信号量-the way to go)
func main() {
   // Execute an HTTP HEAD request for all url's
   // and returns the HTTP status string or an error string.
   stime:=time.Now().UnixNano()


   chan1:=make(chan bool)

   for _, url := range urls {
      //fmt.Println("aaaaa",url)
      go func(url string) {
         stime1:=time.Now().UnixNano()

         resp, err := http.Head(url)
         if err != nil {
            fmt.Println("Error:", url, err)
         }
         etime1:=time.Now().UnixNano()

         fmt.Println(url, ": ", resp.Status,"--",(etime1-stime1)  / 1e6)

         chan1<-true
         //close(chan1)
      }(url)
   }


   for i:=0;i<len(urls);i++{
      _,ok:=<-chan1
      fmt.Println(ok)
   }

         //<-chan1
         //<-chan1
         //<-chan1
         //<-chan1//todo 多一个就不会退出程序了哦  会一直阻塞  
            //todo important 注意 ! 这里也不能用go协程单独运行哦  必须在主程序阻塞这个队列


   //       for i:=range chan1{  //todo  range 会一直阻塞住
   // fmt.Println(i)
   //}

   etime:=time.Now().UnixNano()
   fmt.Println("allfuck",(etime-stime)  / 1e6)

}

您可以自由的转载和修改,但请务必注明文章来源并且不可用于商业目的。
本站大部分内容收集于互联网,如果有侵权内容、不妥之处,请联系删除。敬请谅解!

  关于博主【WANG-FEiHU】

Duplicate
-----------Complicate
--------------------------Appreciate
----------------------------------------[Fate]
-----------------------------------------------Elevate

三人行 有吾师

-------------花有重开日 梦无止境时-------------

  分类目录

  monitor(TD)

岂能尽随人愿,但求无愧我心。

在你内心深处,还有无穷的潜力,有一天当你回首看时,你就会知道这是真的。

活在当下,别在怀念过去或者憧憬未来中浪费掉你现在的生活。

挫折时,要像大树一样,被砍了,还能再长;也要像杂草一样,虽让人践踏,但还能勇敢地活下去。