您的位置 首页 golang

「GCTT 出品」Go 系列教程——24. Select

「GCTT 出品」Go 系列教程——24. Select

Go 系列教程是非常棒的一套初学者教程,入门就它了。

这是 Golang 系列教程 中的第 24 篇。在本章教程中,我们将讨论 Go 语言中的Select。

什么是 select?

select 语句用于在多个发送/接收信道操作中进行选择。select 语句会一直阻塞,直到发送/接收操作准备就绪。如果有多个信道操作准备完毕,select 会随机地选取其中之一执行。该语法与 switch 类似,所不同的是,这里的每个 case 语句都是信道操作。我们好好看一些代码来加深理解吧。

示例

「GCTT 出品」Go 系列教程——24. Select

在上面程序里,server1 函数(第 8 行)休眠了 6 秒,接着将文本 from server1 写入信道 ch。而 server2函数(第 12 行)休眠了 3 秒,然后把 from server2 写入了信道 ch。

而 main 函数在第 20 行和第 21 行,分别调用了 server1 和 server2 两个 Go 协程。

在第 22 行,程序运行到了 select 语句。select 会一直发生阻塞,除非其中有 case 准备就绪。在上述程序里,server1 协程会在 6 秒之后写入 output1 信道,而server2 协程在 3 秒之后就写入了 output2 信道。因此 select 语句会阻塞 3 秒钟,等着 server2 向 output2 信道写入数据。3 秒钟过后,程序会输出:

from server2
 

然后程序终止。

select 的应用

在上面程序中,函数之所以取名为 server1 和 server2,是为了展示 select 的实际应用。

假设我们有一个关键性应用,需要尽快地把输出返回给用户。这个应用的数据库复制并且存储在世界各地的服务器上。假设函数 server1 和 server2 与这样不同区域的两台服务器进行通信。每台服务器的负载和网络时延决定了它的响应时间。我们向两台服务器发送请求,并使用 select 语句等待相应的信道发出响应。select 会选择首先响应的服务器,而忽略其它的响应。使用这种方法,我们可以向多个服务器发送请求,并给用户返回最快的响应了。:)

默认情况

在没有 case 准备就绪时,可以执行 select 语句中的默认情况(Default Case)。这通常用于防止 select 语句一直阻塞。

「GCTT 出品」Go 系列教程——24. Select

上述程序中,第 8 行的 process 函数休眠了 10500 毫秒(10.5 秒),接着把 process successful 写入 ch信道。在程序中的第 15 行,并发地调用了这个函数。

在并发地调用了 process 协程之后,主协程启动了一个无限循环。这个无限循环在每一次迭代开始时,都会先休眠 1000 毫秒(1 秒),然后执行一个 select 操作。在最开始的 10500 毫秒中,由于 process 协程在 10500 毫秒后才会向 ch 信道写入数据,因此 select 语句的第一个 case(即 case v := <-ch:)并未就绪。所以在这期间,程序会执行默认情况,该程序会打印 10 次 no value received。

在 10.5 秒之后,process 协程会在第 10 行向 ch 写入 process successful。现在,就可以执行 select 语句的第一个 case 了,程序会打印 received value: process successful,然后程序终止。该程序会输出:

「GCTT 出品」Go 系列教程——24. Select

死锁 与默认情况

「GCTT 出品」Go 系列教程——24. Select

上面的程序中,我们在第 4 行创建了一个信道 ch。我们在 select 内部(第 6 行),试图读取信道 ch。由于没有 Go 协程向该信道写入数据,因此 select 语句会一直阻塞,导致死锁。该程序会触发运行时 panic,报错信息如下:

「GCTT 出品」Go 系列教程——24. Select

如果存在默认情况,就不会发生死锁,因为在没有其他 case 准备就绪时,会执行默认情况。我们用默认情况重写后,程序如下:

「GCTT 出品」Go 系列教程——24. Select

以上程序会输出:

default case executed
 

如果 select 只含有值为 nil 的信道,也同样会执行默认情况。

「GCTT 出品」Go 系列教程——24. Select

在上面程序中,ch 等于 nil,而我们试图在 select 中读取 ch(第 8 行)。如果没有默认情况,select 会一直阻塞,导致死锁。由于我们在 select 内部加入了默认情况,程序会执行它,并输出:

default case executed
 
「GCTT 出品」Go 系列教程——24. Select

当 select 由多个 case 准备就绪时,将会随机地选取其中之一去执行。

「GCTT 出品」Go 系列教程——24. Select

在上面程序里,我们在第 18 行和第 19 行分别调用了 server1 和 server2 两个 Go 协程。接下来,主程序休眠了 1 秒钟(第 20 行)。当程序控制到达第 21 行的 select 语句时,server1 已经把 from server1 写到了 output1 信道上,而 server2 也同样把 from server2 写到了 output2 信道上。因此这个 select 语句中的两种情况都准备好执行了。如果你运行这个程序很多次的话,输出会是 from server1 或者 from server2,这会根据随机选取的结果而变化。

请在你的本地系统上运行这个程序,获得程序的随机结果。因为如果你在 playground 上在线运行的话,它的输出总是一样的,这是由于 playground 不具有随机性所造成的。

这下我懂了:空 select

「GCTT 出品」Go 系列教程——24. Select

你认为上面代码会输出什么?

我们已经知道,除非有 case 执行,select 语句就会一直阻塞着。在这里,select 语句没有任何 case,因此它会一直阻塞,导致死锁。该程序会触发 panic,输出如下:

「GCTT 出品」Go 系列教程——24. Select

本教程到此结束。祝你愉快。

上一教程 –

下一教程 – Mutex


历史文章:

文章来源:智云一二三科技

文章标题:「GCTT 出品」Go 系列教程——24. Select

文章地址:https://www.zhihuclub.com/101126.shtml

关于作者: 智云科技

热门文章

评论已关闭

37条评论

  1. It s a bit of a hassle to acquire. Outcome measures included development of gestational diabetes, number of first trimester SAB, live births, normal ongoing pregnancies 13 weeks, nature of intrauterine fetal development by sonography, congenital defects, infant birthweight and height, and height, weight, and motor and social development during the first 6 months of life.

  2. Several studies have indeed confirmed that testosterone treatment reduces waist circumference which, in its simplicity, appears to be a valid parameter of the degree of visceral obesity 91.

  3. Macrolides are characterized by a macrocyclic lactone ring containing 14, 15, or 16 atoms with sugars linked via glycosidic bonds. Decrease in dead space in lungs.

  4. 110 100 mg Caja x 24 comps The diversities of healthcare system and polices between countries may be the reason why findings regarding to delay and refuse therapy by breast cancer patients in the current study are significantly different from earlier researches

  5. Organizers have always met stringent cleanup standards, he said, adding that the gathering pumps millions into Nevada s economy Fernando iicjIhyugsOWPMnzpMU 5 29 2022

  6. The low uptake of tamoxifen by American women has previously been explained by concerns over its side effect profile and women s inconsistent perceptions of personal risk Bastian et al, 2001; Meiser et al, 2003; Bober et al, 2004; Melnikow et al, 2005 For example, ligand associated ER is able to interact with and modulate the activity of the nfОєb and Sp1 transcription factors, as well as Fos and Jun heterodimers at AP 1 binding sites see Fig

  7. Between October 1988 and March 1993, 2, 363 node negative, ER positive patients were randomly assigned in B 20 to tamoxifen alone or tamoxifen plus either cyclophosphamide, methotrexate, and fluorouracil or sequential methotrexate and fluorouracil with leucovorin rescue

  8. Data from a phase III trial comparing hippocampal avoidance WBRT plus memantine to WBRT plus memantine alone were recently published Not all tumours that are classified as ERО± positive, however, respond to treatments

  9. Su and her team studied 169 young breast cancer survivors from three academic breast cancer programs, who were all under age 45 It is expected to reach above USD 13

  10. This list may not include all items in this status Your visit will be documented just as any other visit is

  11. It just so happened that the timing coincided with the 6 o clock news, which she always watched

  12. Clinical experience with silymarin in the treatment of chronic liver disease author s transl

  13. So assuming you have any cash to spare, and acknowledging that not everyone is in that fortunate position, where do you think is best to stash your cash

  14. The action of estrogens is manifest from prenatal life during which the exposure to estrogen excess might influence the development of some structures of the male reproductive tract Individuals with heterozygous genotypes experience milder levels of toxicity

  15. Therefore, anticoagulation may be considered in pregnant women with PAH to reduce the risk of VTE 10

  16. 9 BAXTER 100 ml adaptador vial 5 On the other hand, ERs may initiate rapid signaling pathways via the functional coupling of ERs to other receptors

  17. NSABP P 1 studied 13, 388 women with three risk factor profiles 1 age 60 years, 2 age 35 59 years with a Gail model 5 year predicted risk for breast cancer 1 Three Signs You May Have Gingivitis

  18. What I found is there are a large number of quite good studies with a lot of women that show having an occasional glass of wine does not seem to pose a problem, that children of pregnant women who drink occasionally have similar or in some cases even better outcomes than children of women who abstain

  19. 8 Nearly all patients were on vasopressors, most often norepinephrine with an average dose of 0

  20. Neratinib HER Mutation Basket Study SUMMIT Internet Both the cell types were transfected with or without miR 146b mimic 120 p mole well

网站地图