golang select语句执行

官方定义

“select” statement chooses which of a set of possible send or receive operations will proceed. It looks similar to a “switch” statement but with the cases all referring to communication operations.

一个select语句用来选择哪个case中的发送或接收操作可以被立即执行。它类似于switch语句,但是它的case涉及到channel有关的I/O操作.

执行步骤

For all the cases in the statement, the channel operands of receive operations and the channel and right-hand-side expressions of send statements are evaluated exactly once,
in source order, upon entering the "select" statement. The result is a set of channels to receive from or send to, and the corresponding values to send. Any side effects in 
that evaluation will occur irrespective of which (if any) communication operation is selected to proceed. Expressions on the left-hand side of a RecvStmt with a short variable
 declaration or assignment are not yet evaluated.

所有channel表达式都会被求值、所有被发送的表达式都会被求值。求值顺序:自上而下、从左到右. 结果是选择一个发送或接收的channel,无论选择哪一个case进行操作,表达式都会被执行。RecvStmt左侧短变量声明或赋值未被评估。

If one or more of the communications can proceed, a single one that can proceed is chosen via a uniform pseudo-random selection.
Otherwise, if there is a default case, that case is chosen. If there is no default case, the "select" statement blocks until at 
least one of the communications can proceed.

如果有一个或多个IO操作可以完成,则Go运行时系统会随机的选择一个执行,否则的话,如果有default分支,则执行default分支语句,如果连default都没有,则select语句会一直阻塞,直到至少有一个IO操作可以进行.

Unless the selected case is the default case, the respective communication operation is executed.

除非所选择的情况是默认情况,否则执行相应的通信操作。

If the selected case is a RecvStmt with a short variable declaration or an assignment, the left-hand side expressions are evaluated
 and the received value (or values) are assigned.

如果所选case是具有短变量声明或赋值的RecvStmt,则评估左侧表达式并分配接收值(或多个值)。

The statement list of the selected case is executed.

执行所选case中的语句

栗子

var ch1 chan int
var ch2 chan int
var chs = []chan int{ch1, ch2}
var numbers = []int{12345}

func TestSelect(t *testing.T) {

 select {
 case getChan(0) <- getNumber(2):

  fmt.Println("1th case is selected.")
 case getChan(1) <- getNumber(3):

  fmt.Println("2th case is selected.")
 default:
 
 fmt.Println("default!.")
 }
}

func getNumber(i int) int {
 fmt.Printf("numbers[%d]n", i)

 return numbers[i]
}
func getChan(i int) chan int {
 fmt.Printf("chs[%d]n", i)

 return chs[i]
}

执行结果

有default 无阻塞

=== RUN   TestSelect
chs[0]
numbers[2]
chs[1]
numbers[3]
default!.
--- PASS: TestSelect (0.00s)
PASS

无default 阻塞

=== RUN   TestSelect
chs[0]
numbers[2]
chs[1]
numbers[3]


原文始发于微信公众号(码农札记):golang select语句执行

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由半码博客整理,本文链接:https://www.bmabk.com/index.php/post/98643.html

(0)
小半的头像小半

相关推荐

发表回复

登录后才能评论
半码博客——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!