package main import ( "fmt" "time" ) func main() { // Case-1: no buffer //chanMessage := make(chan string) // Case-2: with buffer ... the output changes chanMessage := make(chan string, 2) count := 4 go func() { for i := 1; i <= count; i++ { fmt.Println("send message") // send to chanMessage chanMessage <- fmt.Sprintf("message %d", i) } }() // Pause the main to let the goroutine sends its messages time.Sleep(time.Second * 2) for i := 1; i <= count; i++ { // receive from chanMessage and print fmt.Println(<-chanMessage) time.Sleep(time.Second) } }
buffer 2 表示能缓冲2个,实际上能send 3个。第4个才发生阻塞。
output: send message send message send message message 1 send message message 2 message 3 message 4
+5 level:2 exp:10/50
有疑问加站长微信联系(非本文作者)