package main import ( "fmt" "sync" "time" ) var workers = 3 func processItem(input <-chan int, output chan<- int, wg *sync.WaitGroup) { for { fmt.Println("=") in := <-input fmt.Printf("Working on input: %v\n", in) output <- in + 1 wg.Done() } } func main() { items := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} var wg sync.WaitGroup wg.Add(len(items)) out := make(chan int, len(items)) in := make(chan int) for i := 0; i < workers; i++ { go processItem(in, out, &wg) } for _, val := range items { in <- val } wg.Wait() total := 0 for j := 0; j < len(items); j++ { total += <-out } fmt.Printf("Total sum is : %v\n", total) time.Sleep(20 * time.Second) }
zzh@ZZHPC:/zdata/Github/ztest$ go run main.go = Working on input: 1 = Working on input: 2 = Working on input: 3 = Working on input: 4 = Working on input: 5 = Working on input: 6 = Working on input: 7 = Working on input: 8 = Working on input: 9 = Working on input: 10 = Total sum is : 65 = =
"Working on input"输出有10个,"="输出有13个,函数processItem中的for循环执行到语句“in := <-input”,其一直在等待数据,该程序运行了20s,主进程结束,for循环所在的子进程被强行中止。