package main import ( "fmt" ) func main() { done := make(chan struct{}, 4) exit := make(chan struct{}) go func () { //defer close exit 依然会deadlock //done 通道只有1次write,有2次read //done 则在exit close前先产生deadlock defer close(exit) fmt.Println("Goroutine start.") fmt.Println("len cap",len(done), cap(done)) d, ok := <-done if !ok { fmt.Println("done closed") } else { fmt.Println("done not closed", d, done) } //此处close 则当前goroutine立即停止执行 //因为done 在主goroutine 有 1次write 1次read,main底部的exit不再阻塞 //主 goroutine 提前退出 //close(exit) _, ok = <-done if !ok { fmt.Println("done closed 1") } fmt.Println("Goroutine emptyChan finished") }() done <- struct{}{} <-exit fmt.Println("main done") } func closeNoDeadLock() { done := make(chan struct{}) c := make(chan int) go func () { defer close(done) fmt.Println("goroutine start") for { select{ case v, ok := <-c: if !ok { fmt.Println("c closed", v,ok) return } fmt.Println("c not closed", v,ok) } } fmt.Println("goroutine emptyChan finished") }() c <- 11 close(c) <-done fmt.Println("main done") }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)