buffered channel
For non-buffered channels, both sending and receiving are blocked. With buffered channels, there is a buffer area that can continue to send and receive data.
The make(chan T, size)
buffer is full, the program will be blocked
ch1:=make(chan int, 5)
ch1 <- 100//no blocking, because there is a cache
ch1 <- 200//
ch1 <- 300
ch1 <- 400
ch1 <- 500
...//buffer is full
ch1 <- 600 // blocked program
package main import ( "fmt" "strconv" "time" ) func main () { /* Non-cached channel: make(chan T) Cached channel: make(chan T, size) cached channel, understood as a queue: non-cached, sending or receiving, all are blocked. Cached channel, buffered area When the data is full, it will block. . */ ch1 := make ( chan int ) //uncached channel fmt.Println(len(ch1) , cap(ch1)) //0 0 //ch1 <- 100//blocked, need other goroutines to release Block, otherwise deadlock ch2 := make ( chan int , 5 ) // buffered channel, buffer size is 5 fmt.Println(len(ch2) , cap(ch2)) //0 5 ch2 <- 100 // fmt.Println(len(ch2), cap(ch2)) //1 5 //ch2 <- 200 //ch2 <- 300 //ch2 <- 400 //ch2 <- 500 //ch2 <- 600 fmt.Println("--------------") ch3 := make(chan string, 4) go sendData3(ch3) for { time.Sleep(1*time.Second) v, ok := <-ch3 if !ok { fmt.Println( "Finished," , ok) break } fmt.Println( "\t The data read is: " , v) } fmt.Println("main...over...") } func sendData3(ch3 chan string) { for i := 0; i < 10; i++ { ch3 <- "数据" + strconv.Itoa(i) fmt.Println( "Sub-goroutine, write out the first " , i , "data" ) } close(ch3) }