| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "time" |
| 6 | ) |
| 7 | |
| 8 | func main() { |
| 9 | c1 := make(chan string) |
| 10 | c2 := make(chan string) |
| 11 | |
| 12 | go func() { |
| 13 | time.Sleep(1e8) |
| 14 | c1 <- "one" |
| 15 | }() |
| 16 | go func() { |
| 17 | time.Sleep(2e8) |
| 18 | c2 <- "two" |
| 19 | }() |
| 20 | |
| 21 | for i := 0; i < 2; i++ { |
| 22 | fmt.Println("start for") |
| 23 | select { |
| 24 | case msg1 := <-c1: |
| 25 | fmt.Println("received", msg1) |
| 26 | fmt.Println("finish 1") |
| 27 | case msg2, ok := <-c2: |
| 28 | fmt.Println("received #2", msg2, ok) |
| 29 | } |
| 30 | fmt.Println("end for") |
| 31 | } |
| 32 | fmt.Println("Bye") |
| 33 | } |
| 34 | |
| 35 | // Output: |
| 36 | // start for |
| 37 | // received one |
| 38 | // finish 1 |
| 39 | // end for |
| 40 | // start for |
| 41 | // received #2 two true |
| 42 | // end for |
| 43 | // Bye |