Advertisement
cwchen

[Go] Selecting among different channels.

Nov 28th, 2017
1,089
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.71 KB | None | 0 0
  1. package main
  2.  
  3. import "time"
  4. import "fmt"
  5.  
  6. func main() {
  7.     // For our example we'll select across two channels.
  8.     c1 := make(chan string)
  9.     c2 := make(chan string)
  10.  
  11.     // Each channel will receive a value after some amount
  12.     // of time, to simulate e.g. blocking RPC operations
  13.     // executing in concurrent goroutines.
  14.     go func() {
  15.         time.Sleep(time.Second * 1)
  16.         c1 <- "one"
  17.     }()
  18.     go func() {
  19.         time.Sleep(time.Second * 1)
  20.         c2 <- "two"
  21.     }()
  22.  
  23.     // We'll use `select` to await both of these values
  24.     // simultaneously, printing each one as it arrives.
  25.     for i := 0; i < 2; i++ {
  26.         select {
  27.         case msg1 := <-c1:
  28.             fmt.Println("received", msg1)
  29.         case msg2 := <-c2:
  30.             fmt.Println("received", msg2)
  31.         }
  32.     }
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement