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) time.Sleep(2 * time.Second) 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) }
zzh@ZZHPC:/zdata/MyPrograms/Go/ddd$ 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”而退出的(从空channel中接收不到数据会导致goroutine异常退出)。
标签:processItem,Working,go,Go,input,receiving,channel From: https://www.cnblogs.com/zhangzhihui/p/17733125.html