This is a creation in Article, where the information may have evolved or changed.
1. Code
2. Operation
3. Analysis
1. Code Buffer.go
1 PackageMain2 3 Import (4"FMT"5"Time"6 )7 8Func readthread (Ch chanint) {9Fmt. Println ("Read for reading ...")Ten forI: =Range CH { OneFmt. Println ("Get I:", i) A if20 = =I { - Break - } the Time . Sleep (1e8) - } -Fmt. Println ("Read over ...") - } + - Func Main () { +CH: = Make (chanint, 1024) A go readthread (CH) atTime. Sleep (1E9 * 2) - forI: = 1; I <= 20; i++ { -CH <-I - } -Fmt. Println ("Waitting for reading ...") -Time. Sleep (1E9 * 3) inFmt. Println ("Over ...") -}
2. Operation
1 $ go Run buffer.go2Read forreading ...3Waitting forreading ...4Get I:15Get I:26Get I:37Get I:48Get I:59Get I:6TenGet I:7 OneGet I:8 AGet I:9 -Get I:10 -Get I:11 theGet I:12 -Get I:13 -Get i:14 -Get i:15 +Get I:16 -Get i:17 +Get i:18 AGet i:19 atGet i:20 - Read over ... -Over ...
3. Analysis
Analysis based on the results of the operation:
1) First run Readthread read thread, read thread is ready to read, but at this time there is no data in the channel, so blocked. Wait for the read action.
2) The main thread, one-time to the channel to write a large amount of data, because of the buffer mechanism, so you can write multiple data at once without blocking. When the main thread finishes writing the data, it begins to wait for the read thread to end.
3) data is started in the channel, the read thread starts reading the data, reads one data every 0.1 seconds, reads 20 times altogether. Read finished, print read over.
4) Main thread wait time is up, return, exit