Go Buffer

Golang并发(四)- buffered channel 和 Worker Pools

╄→尐↘猪︶ㄣ 提交于 2019-12-10 01:28:34
What you are wasting today is tomorrow for those who died yesterday; what you hate now is the future you can not go back. 你所浪费的今天是昨天死去的人奢望的明天; 你所厌恶的现在是未来的你回不去的曾经。 Buffered channel 之前我们说的channel都是不带缓冲的,无论发送和接收都会导致阻塞。 缓冲Channel的特点是:只有当发送至缓冲区存满后导致阻塞, 接受也是如此。 创建方式: ch:= make(chan Type , capacity) capacity 容量, 当capacity = 0 时, 为无缓冲channel,通常省略而已。 package main import ( "fmt" ) func main() { ch := make(chan string, 2) ch <- "naveen" ch <- "paul" fmt.Println(<- ch) fmt.Println(<- ch) // 注释此行,会不会deadlock??? } 下这个例子请认真思考,有助于理解buffered channel: package main import ( "fmt" "time" ) func write(ch chan int)