1. Code
2. Operation
3. Analysis
1. Code
1 PackageMain2 3 Import (4"Time"5"FMT"6 )7 8Func waitFor (Ch chanint) {9Fmt. Println (time. Now (), "Writing ...")Ten Time . Sleep (1E9) OneCH <-10 AFmt. Println (time. Now (), "wrote ...") - } - the Func Main () { -var a chanint= Make (chanint) -var b chanint= Make (chanint) -var ch chanint= Make (chanint) + - go waitFor (CH) + Avar rint= 0 atFmt. Println (time. Now (), "SELECT ...") - Select { - Casex: = <-A: -Fmt. Println (time. Now (), "read from a ...") -R =x - Casex: = <-B: inFmt. Println (time. Now (), "read from B ...") -R =x to Casex: = <-Ch: +Fmt. Println (time. Now (), "read from CH ...") -R =x the } *Fmt. Println (time. Now (), "Select over.., R =", R) $ Time . Sleep (1E9)Panax NotoginsengFmt. Println (time. Now (), "over..") -}
2. Operation
12 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 = 7 2015-07-19 00:35:25.888486739 +0800 CST over..
3. Analysis
1) Select in the main thread starts running, blocking waits for 3 channel in Select
2) write data to CH WAITFOR in thread (co-process)
3) Select receives data for reading
4) Main thread exit
Go language exercise: Channel Select timeout mechanism