← 返回 Golang 列表

Go 并发编程:channel 与 select

Don't communicate by sharing memory; share memory by communicating。深入 channel 与 select 模式。

Channel 基础

package main

import ("fmt")

func main() {
  ch := make(chan string)
  go func() {
    ch <- "hello from goroutine"
  }()
  fmt.Println(<-ch)
}

Select 多路复用

select {
case msg := <-ch1:
  fmt.Println("ch1: " + msg)
case msg := <-ch2:
  fmt.Println("ch2: " + msg)
default:
  fmt.Println("no message")
}
提示: 无缓冲 channel 是同步的,有缓冲 channel 发送不会阻塞直到缓冲区满。