1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
| package main
import ( "fmt" "sync" "time" )
func httpGet(url int, response chan string, rep chan string, limiter chan bool, wg *sync.WaitGroup) { defer wg.Done() response <- fmt.Sprintf("http get: %d", url) time.Sleep(time.Second * 5) rep <- fmt.Sprintf("rep get: %d", url) <-limiter }
func collect(urls []int) ([]string, []string) { var result []string var tworesult []string wg := &sync.WaitGroup{} limiter := make(chan bool, 5) defer close(limiter)
responseChannel := make(chan string, 20) repChannel := make(chan string, 20) wgResponse := &sync.WaitGroup{}
wgResponse.Add(2) go func() { for response := range responseChannel { fmt.Println("test01") result = append(result, response) } wgResponse.Done() }() go func() { for rep := range repChannel { fmt.Println("test02") tworesult = append(tworesult, rep) } wgResponse.Done() }() for _, url := range urls { wg.Add(1) limiter <- true go httpGet(url, responseChannel, repChannel, limiter, wg) }
wg.Wait() fmt.Println("所有协程已执行完毕")
close(responseChannel) close(repChannel)
wgResponse.Wait()
return result, tworesult }
func main() { urls := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} result, tworesult := collect(urls) fmt.Println(result) fmt.Println(tworesult) }
|