GO语言练习:channel select 超时机制
1、代码
2、运行
3、解析
1、代码
1 package main
2
3 import (
4 "time"
5 "fmt"
6 )
7
8 func waitFor(ch chan int) {
9 fmt.Println(time.Now(), "writing ...")
10 time.Sleep(1e9)
11 ch <- 10
12 fmt.Println(time.Now(), "wrote ...")
13 }
14
15 func main() {
16 var a chan int = make(chan int)
17 var b chan int = make(chan int)
18 var ch chan int = make(chan int)
19
20 go waitFor(ch)
21
22 var r int = 0
23 fmt.Println(time.Now(), "select ...")
24 select {
25 case x := <-a :
26 fmt.Println(time.Now(), "read from a...")
27 r = x
28 case x := <-b :
29 fmt.Println(time.Now(), "read from b...")
30 r = x
31 case x := <-ch :
32 fmt.Println(time.Now(), "read from ch...")
33 r = x
34 }
35 fmt.Println(time.Now(), "select over.., r = ", r)
36 time.Sleep(1e9)
37 fmt.Println(time.Now(), "over..")
38 }
2、运行
1 $ go run timeout.go
2 2015-07-19 00:35:23.859684465 +0800 CST select ...
3 2015-07-19 00:35:23.861022451 +0800 CST writing ...
4 2015-07-19 00:35:24.864462549 +0800 CST wrote ...
5 2015-07-19 00:35:24.865185396 +0800 CST read from ch...
6 2015-07-19 00:35:24.874655353 +0800 CST select over.., r = 10
7 2015-07-19 00:35:25.888486739 +0800 CST over..
3、解析
1)主线程中的select开始运行,对select中的3个channel进行阻塞等待
2)在线程(协程)waitFor中向ch写入数据
3)select收到数据,进行读取
4)主线程退出
作 者:fengbohello
个人网站:http://www.fengbohello.top/
E-mail : fengbohello@foxmail.com
欢迎转载,转载请注明作者和出处。
因作者水平有限,不免出现遗漏和错误。希望热心的同学能够帮我指出来,我会尽快修改。愿大家共同进步,阿里嘎多~
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步