go版本: go1.12.5 linux/amd64
我试图理解 Go 中的 nil 通道。
package main
import (
"fmt"
"sync"
)
func main() {
ch := make(chan int)
ch2 := make(chan int)
wg := sync.WaitGroup{}
wg.Add(1)
go func(c1 chan int, c2 chan int, w *sync.WaitGroup) {
for c1 != nil || c2 != nil {
fmt.Println("in for")
fmt.Println(c1, c2)
select {
case v, ok := <-c1:
if !ok {
c1 = nil
fmt.Println("c1 closed")
} else {
fmt.Println(v, " recieved c1")
}
case v, ok := <-c2:
if !ok {
c2 = nil
} else {
fmt.Println(v, " recieved c2")
}
}
}
fmt.Println("called wg.Done")
wg.Done()
}(ch, ch2, &wg)
for i := 0; i < 4; i++ {
if i%2 == 0 {
ch <- i
} else {
ch2 <- i
}
}
close(ch)
wg.Wait()
}
并在标准输出上收到此输出:
in for
0xc000084060 0xc0000840c0
0 recieved c1
in for
0xc000084060 0xc0000840c0
1 recieved c2
in for
0xc000084060 0xc0000840c0
2 recieved c1
in for
0xc000084060 0xc0000840c0
3 recieved c2
in for
0xc000084060 0xc0000840c0
c1 closed
in for
<nil> 0xc0000840c0
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [semacquire]:
sync.runtime_Semacquire(0xc00009a018)
/usr/local/go/src/runtime/sema.go:56 +0x39
sync.(*WaitGroup).Wait(0xc00009a010)
/usr/local/go/src/sync/waitgroup.go:130 +0x65
main.main()
/home/ayush/projects/gojects/src/go-practice/nil-channels/main.go:44 +0x155
goroutine 18 [select]:
main.main.func1(0xc00009a010, 0xc000084060, 0xc0000840c0, 0xc00009a010)
/home/ayush/projects/gojects/src/go-practice/nil-channels/main.go:17 +0x1e5
created by main.main
/home/ayush/projects/gojects/src/go-practice/nil-channels/main.go:13 +0xce
exit status 2
但根据代码和日志,wg.Done()从未被调用过,这意味着 goroutine 仍然存在。
谁能帮我理解这里发生了什么?
慕沐林林
人到中年有点甜
相关分类