Go协程,用通道传输数据

Go协程,用通道传输数据


func GolistChanTest() {
 
	loopTimes := 10
	log.Infof("start")  
	gn := make(chan int, 2)
	listChan:= make(chan map[int]string, int(loopTimes))
	wg := sync.WaitGroup{}
	loopEndTime := loopTimes - 1
	for i := 0; i < int(loopTimes); i++ {
		wg.Add(1)
		gn <- 1

		go func(page int) {
			defer func() {
				wg.Done()
				<-gn
			}()

			list := make(map[int]string)

			for i := 0; i < 10; i++ {
				list[page*10+i] = fmt.Sprintf("=%d*10+%d", page, i)
			}

			listChan<- list

			if loopEndTime <= page {
				close(listChan)
			}

			time.Sleep(300 * time.Millisecond)

		}(i)
	}

	result := make(map[int]string, 0)
	for num := range listChan{ // 从通道中读取数据,直到通道关闭
		for key, value := range num {
			result[key] = value 
		}
	}

	wg.Wait()
	close(gn)

	log.Infof("result :%+v", result)
}

你可能感兴趣的:(go开发,golang,服务器)