我正在尝试编写一个事件侦听器并尝试控制侦听器内的状态流。我知道我错过了一些使用 channel 的原则,代码可能看起来很愚蠢。但是,如果有人能帮助我了解我的错误是什么以及如何改进它,我将不胜感激。此代码无法工作:package mainimport ( "fmt" "time")type A struct { count int ch chan bool exit chan bool}func (this *A) Run() { for { select { case <-this.ch: this.handler() case <-this.exit: return default: time.Sleep(20 * time.Millisecond) } }}func (this *A) handler() { println("hit me") if this.count > 2 { this.exit <- true } fmt.Println(this.count) this.count += 1}func (this *A) Hit() { this.ch <- true}func main() { a := &A{} a.ch = make(chan bool) a.exit = make(chan bool) go a.Hit() go a.Hit() go a.Hit() go a.Hit() a.Run() fmt.Println("s")}它引发错误:hit me0 hit me1hit me2hit mefatal error: all goroutines are asleep - deadlock!goroutine 1 [chan send]:main.(*A).handler(0x2101bf000)/Users/yeer/go/src/github.com/athom/practice/channel-controll.go:31 +0x60main.(*A).Run(0x2101bf000)/Users/yeer/go/src/github.com/athom/practice/channel-controll.go:19 +0x66main.main()/Users/yeer/go/src/github.com/athom/practice/channel-controll.go:50 +0xedexit status 2
1 回答
- 1 回答
- 0 关注
- 176 浏览
添加回答
举报
0/150
提交
取消