前言

selectswitch
select
select

语法格式:

defaultbreakreturn
select
defaultdefault
selectdefaultdefaultselectdefault
selectbreak

程序示例

goroutine_select.goch1ch2
pump1()pump2()suck()
ch1ch2pump1()pump2()suck()selectch1ch2

运行结果:

Received on channel 2: 148120
Received on channel 2: 148121
Received on channel 2: 148122
Received on channel 2: 148123
Received on channel 2: 148124
Received on channel 2: 148125
Received on channel 2: 148126
Received on channel 1: 296784
Received on channel 2: 148127
Received on channel 2: 148128
Received on channel 2: 148129
Received on channel 1: 296786
Received on channel 1: 296788

一秒内的输出非常惊人,如果我们给它计数(goroutine_select2.go),得到了 296788 个左右的数字。

select 特性预览

管道读写

select
  • 如果管道中没有缓存,如下:
select
  • 如果管道中有缓冲区且还可以存放至少一个数据,如下:

此时,管道可以写入,写操作对应的 case 语句得到执行,且执行结束后函数退出。

  • 如果管道有缓冲区且缓冲区中已放满数据,如下:

此时,管道可以读取,读操作对应的 case 语句得到执行,且执行结束后函数退出。

  • 管道有缓冲区,缓冲区中已有部分数据还可以存入数据,如下:
select

总结

select 的每个 case 语句只能操作一个管道,要么写入数据,要么读取数据;

如果管道中没有数据读取操作则会阻塞,如果管道中没有空余的缓冲区则写入操作会阻塞;

当 select 的多个 case 语句中的管道均阻塞时,整个 select 语句也会陷入阻塞,直到任意一个管道解除阻塞;

如果多个 case 语句均没有阻塞,那么 select 将随机挑选一个 case 执行。