亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

關于通道控制流的困惑

關于通道控制流的困惑

Go
慕容3067478 2021-07-07 21:30:13
我正在嘗試編寫一個事件偵聽器并嘗試控制偵聽器內的狀態流。我知道我錯過了一些使用 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 關注
  • 198 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號