-
channel存在3种状态:
-
nil,未初始化的状态,只进行了声明,或者手动赋值为nil
-
active,正常的channel,可读或者可写
-
closed,已关闭,千万不要误认为关闭channel后,channel的值是nil
-
当需要不断从channel读取数据时,使用for range,当channel关闭时,for循环会自动退出,无需主动监测channel是否关闭
-
for x := range ch{
fmt.Println(x)
}
- 读channel,但不确定channel是否关闭时,可用ok进行判断,ok为true时读到数据且通道没有关闭
if v, ok := <- ch; ok {
fmt.Println(v)
}
- 要对多个通道进行同时处理,但只处理最先发生的channel时,select可以同时监控多个通道的情况,只处理未阻塞的case。当通道为nil时,对应的case永远为阻塞,无论读写。特殊关注:普通情况下,对nil的通道写操作是要panic的
// 分配job时,如果收到关闭的通知则退出,不分配job
func (h *Handler) handle(job *Job) {
select {
case h.jobCh<-job:
return
case <-h.stopCh:
return
}
}
- 协程对某个通道只读或只写时,
- 如果协程对某个channel只有写操作,则这个channel声明为只写
- 如果协程对某个channel只有读操作,则这个channe声明为只读
// 只有generator进行对outCh进行写操作,返回声明
// <-chan int,可以防止其他协程乱用此通道,造成隐藏bug
func generator(int n) <-chan int {
outCh := make(chan int)
go func(){
for i:=0;i<n;i++{
outCh<-i
}
}()
return outCh
}
// consumer只读inCh的数据,声明为<-chan int
// 可以防止它向inCh写数据
func consumer(inCh <-chan int) {
for x := range inCh {
fmt.Println(x)
}
}
- 使用缓冲channel增强并发和异步
- 有缓冲通道是异步的,无缓冲通道是同步的
- 有缓冲通道可供多个协程同时处理,在一定程度可提高并发性
// 无缓冲,同步
ch1 := make(chan int)
ch2 := make(chan int, 0)
// 有缓冲,异步
ch3 := make(chan int, 1)
// 使用5个`do`协程同时处理输入数据
func test() {
inCh := generator(100)
outCh := make(chan int, 10)
for i := 0; i < 5; i++ {
go do(inCh, outCh)
}
for r := range outCh {
fmt.Println(r)
}
}
func do(inCh <-chan int, outCh chan<- int) {
for v := range inCh {
outCh <- v * v
}
}
- 需要超时控制的操作,使用select和time.After,看操作和定时器哪个先返回,处理先完成的,就达到了超时控制的效果
func doWithTimeOut(timeout time.Duration) (int, error) {
select {
case ret := <-do():
return ret, nil
case <-time.After(timeout):
return 0, errors.New("timeout")
}
}
func do() <-chan int {
outCh := make(chan int)
go func() {
// do work
}()
return outCh
}
- 使用time实现channel无阻塞读写。是为操作加上超时的扩展,这里的操作是channel的读或写
func unBlockRead(ch chan int) (x int, err error) {
select {
case x = <-ch:
return x, nil
case <-time.After(time.Microsecond):
return 0, errors.New("read time out")
}
}
func unBlockWrite(ch chan int, x int) (err error) {
select {
case ch <- x:
return nil
case <-time.After(time.Microsecond):
return errors.New("read time out")
}
}
- 使用close(ch)关闭所有下游协程,所有读ch的协程都会收到close(ch)的信号
func (h *Handler) Stop() {
close(h.stopCh)
// 可以使用WaitGroup等待所有协程退出
}
// 收到停止后,不再处理请求
func (h *Handler) loop() error {
for {
select {
case req := <-h.reqCh:
go handle(req)
case <-h.stopCh:
return
}
}
}
- 使用chan struct{}作为信号channel,当使用channel传递信号,而不是传递数据时,,没数据需要传递时,传递空struct
// 上例中的Handler.stopCh就是一个例子,stopCh并不需要传递任何数据
// 只是要给所有协程发送退出的信号
type Handler struct {
stopCh chan struct{}
reqCh chan *Request
}
- 使用channel传递结构体数据时,传递结构体的指针而非结构体,,channel本质上传递的是数据的拷贝,拷贝的数据越小传输效率越高,传递结构体指针,比传递结构体更高效
reqCh chan *Request
// 好过
reqCh chan Request