go随聊-chan使用的坑

Go中chan是分阻塞和非阻塞(带缓冲)的

创建非缓冲的chan

ch:=make(chan int)
ch<-1
fmt.Println("run")

运行会报:fatal error: all goroutines are asleep - deadlock!  因为这种方式创建的是非缓冲的chan

创建带缓冲的chan

ch:=make(chan int,1)
ch<-1
fmt.Println("run")

缓冲数目少了同样也会阻塞

ch:=make(chan int,1)
ch<-1
ch<-1
fmt.Println("run")

运行会报:fatal error: all goroutines are asleep - deadlock! 

使用chan进行协程优雅退出

go func(){
    for {
        select {
        case <-time.After(time.Second * 10):
        case <-this.signal:
            this.signal<-1
            return
        }
    }
}()
func (this *xxxx) Stop() {
	this.signal<-1
	<-this.signal
	close(this.signal)
}

猜你喜欢

转载自blog.csdn.net/yimin_tank/article/details/83348789
今日推荐