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
| var c chan string
func Pingpong() { i := 0 for { fmt.Println(<-c) c <- fmt.Sprintf("From Pingpong: Hi, #%d", i) i++ } }
func main() { c = make(chan string) go Pingpong() for i := 0; i < 10; i++ { c <- fmt.Sprintf("From main: Hello, #%d", i) fmt.Println(<-c) } }
输出: From main: Hello, #0 From Pingpong: Hi, #0 From main: Hello, #1 From Pingpong: Hi, #1 From main: Hello, #2 From Pingpong: Hi, #2 From main: Hello, #3 From Pingpong: Hi, #3 From main: Hello, #4 From Pingpong: Hi, #4 From main: Hello, #5 From Pingpong: Hi, #5 From main: Hello, #6 From Pingpong: Hi, #6 From main: Hello, #7 From Pingpong: Hi, #7 From main: Hello, #8 From Pingpong: Hi, #8 From main: Hello, #9 From Pingpong: Hi, #9
|