buffered channel有缓冲区,缓存区满了,才会阻塞。
A send on a channel happens before the corresponding receive from that channel completes.
var c = make(chan int, 3)
var a string
func f() {
a = "hello, world"
c <- 0
}
func main() {
go f()
<-c
print(a)
}
这里说「发送」happens-before「接收」。是不是就可以理解,可执行的代码上先有「发送」,然后才执行接收?
但是又有一个rule:
The kth receive on a channel with capacity C happens before the k+Cth send from that channel completes.
var work []func()
var limit = make(chan int, 3)
func main() {
work = []func(){
func() {
fmt.Println("Work1")
time.Sleep(time.Second)
},
func() {
fmt.Println("Work2")
time.Sleep(time.Second)
},
func() {
fmt.Println("Work3")
time.Sleep(time.Second)
},
func() {
fmt.Println("Work4")
time.Sleep(time.Second)
},
}
wg := sync.WaitGroup{}
for _, w := range work {
wg.Add(1)
go func(w func()) {
limit <- 1
w()
<-limit
wg.Done()
}(w)
}
wg.Wait()
}
这里又说接收「第k次的接收」happens-before「k+缓冲区size的发送」。这里是不是在限定,在第一轮“缓冲区满时”的接收必须happens-before在第二轮发送的开始?