我正在嘗試編寫一個事件偵聽器并嘗試控制偵聽器內(nèi)的狀態(tài)流。我知道我錯過了一些使用 channel 的原則,代碼可能看起來很愚蠢。但是,如果有人能幫助我了解我的錯誤是什么以及如何改進(jìn)它,我將不勝感激。此代碼無法工作: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")}它引發(fā)錯誤: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 回答
- 0 關(guān)注
- 193 瀏覽
添加回答
舉報
0/150
提交
取消