有这个代码:
package main
import (
"fmt"
"time"
)
func main() {
ch := make(chan bool)
var counter int
for i:=0; i < 100; i++ {
go func() {
ch<-true
counter++
<-ch
}()
}
time.Sleep(5*time.Second)
fmt.Println(counter)
}
为什么计数器不增加?
为什么理论上通道不能用作互斥体?
ch := make(chan bool)创建一个无缓冲通道,即通道容量为 0。通道通常同步工作 - 每一方都等待对方能够接收或发送消息。但是缓冲通道异步工作 - 接收或发送消息不会导致各方停止。换句话说,直到频道中有读者,
ch<-true它才会挂起。如果将通道容量更改为 1,则问题将消失。
改成
ch := make(chan bool, 1)https://play.golang.org/p/vKoeSInFIzA