funcsleepyGopher(i int, c chanint) { time.Sleep(3 * time.Second) fmt.Println(i, "...zzZZ...") c <- i } funcmain() { c := make(chanint) for i := 0; i < 5; i++ { go sleepyGopher(i, c) } for i := 0; i < 5; i++ { gopherID := <-c fmt.Println("gopher", gopherID, "has finished sleeping") }
funcsourceGopher(downstream chanstring) { for _, v := range []string{"hello world", "a bad apple", "goodbye all"} { downstream <- v } downstream <- "" }
funcfilterGopher(upstream, downstream chanstring) { for { item := <-upstream if item == "" { downstream <- "" return } if !strings.Contains(item, "bad") { downstream <- item } } } funcprintGopher(upstream chanstring) { for { v := <-upstream if v == "" { return } fmt.Println(v) } }
funcmain() { c0 := make(chanstring) c1 := make(chanstring) go sourceGopher(c0) go filterGopher(c0, c1) printGopher(c1) }
funcsourceGopher(downstream chanstring) { for _, v := range []string{"hello world", "a bad apple", "goodbye all"} { downstream <- v } close(downstream) }
funcfilterGopher(upstream, downstream chanstring) { for item := range upstream {//for range 可以遍历通道(channel),但是通道在遍历时,只输出一个值,即管道内的类型对应的数据 if !strings.Contains(item, "bad") { downstream <- item } } close(downstream) } funcprintGopher(upstream chanstring) { for k := range upstream { fmt.Println(k) } }
funcmain() { c0 := make(chanstring) c1 := make(chanstring) go sourceGopher(c0) go filterGopher(c0, c1) printGopher(c1) }