select 是 Go 中的一个控制结构,类似于用于通信的 switch 语句。每个 case 必须是一个通信操作,要么是发送要么是接收(菜鸟教程的解析),学过C语言应该对switch有所了解,下面看一个实例。

package main

import (
 "fmt"
 "time"
)

func Chann(ch, sh chan int, stopCh chan bool) {
 for j := 0; j < 5; j++ {
  if j%2 == 0{
   ch <- j
  }else{
   sh <- j
  }
  time.Sleep(time.Second)
 }
 stopCh <- true
}

func main() {

 ch := make(chan int)
 sh := make(chan int)
 stopCh := make(chan bool)

 go Chann(ch,sh, stopCh)

 for {
  select {
  case c := <-ch:
   fmt.Println("Recvice ch:", c)
  case s := <-sh:
   fmt.Println("Receive sh:", s)
  case _ = <-stopCh:
   goto end
  }
 }
end:
 fmt.Println("end")
}

    运行:Recvice ch:0

               Recvice ch:1

               Recvice ch:2

               Recvice ch:3

               Recvice ch:4

   有一个协程在在往chan写数据,select里面读取数据。

09-04 09:23