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)主线程退出
有疑问加站长微信联系(非本文作者)