请求之间超时的演示是怎样运行原理

来源:6-4 Select

qq_永远的稻米_0

2022-06-13 19:30:43

相关截图:

https://img.mukewang.com/climg/62a71e1309fcede313540518.jpg

我理解前三个case是在执行,当for循环发现c1,c2没有发数据的时候,case也不会收数据,这个时候,走到了case <-time.After(800 * time.Millisecond) 800ms,第一次走到是send?在800ms没有c1,c2的数据生成,就会不停的走到这个case <-time.After(800ms)?那800ms的超时间隔不是被重置了么?

写回答

1回答

ccmouse

2022-06-19

文档里是这样规定的:

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.

第一步,注意此时还没有发生channel收发,先把所有的case里的操作数进行运算(evaluate),而且是根据代码中的顺序,而且仅运算一次。

这里除了c1,c2,activeValue,还会运算time.After(...),这个运算结果是一个channel,这个channel会在800毫秒之后送入一个值。(可具体查看time.After的定义),假设叫t,就相当于做了:

t:=time.After(...)

case <-t:

第二步,所有分支运算完毕,进入收发逻辑。哪个分支最先有数据,就选择哪个分支。如果同时有数据,就随机选择。

这里如果c1,c2没能在800毫秒内送来数据,那么800毫秒以后必将选择我们处理超时的那个分支。


0

0 学习 · 1399 问题

查看课程

相似问题