有段代码:建了5个协程分别向5个channel里写1,然后遍历channel数组读数据。
``` go
package main
import ( "fmt" )
func Count(i int, ch chan int) {
ch <- 1
fmt.Printf("seq: %d, counting\n", i)
}
func main() {
chs := make([]chan int, 5)
for n := 0; n < 5; n++ {
chs[n] = make(chan int)
go Count(n, chs[n])
}
for _, ch := range(chs) {
<-ch
}
}
```
然后第5个协程(seq:4)的执行结果在gdb里是Ok的,直接执行却没有。为啥gdb调试和直接执行的结果不一样~~!
预期的结果是:
```
seq: 0, counting
seq: 1, counting
seq: 2, counting
seq: 3, counting
seq: 4, counting
```
实际运行结果:
```
➜ testing-ground ./ch
seq: 0, counting
seq: 1, counting
seq: 2, counting
seq: 3, counting
```
gdb调试时的结果:
```
16 for _, ch := range(chs) {
(gdb)
seq: 0, counting ⭐
17 <-ch
(gdb)
seq: 1, counting ⭐
16 for _, ch := range(chs) {
(gdb)
17 <-ch
(gdb)
seq: 2, counting ⭐
16 for _, ch := range(chs) {
(gdb)
17 <-ch
(gdb)
16 for _, ch := range(chs) {
(gdb)
seq: 3, counting ⭐
17 <-ch
(gdb)
seq: 4, counting ⭐
16 for _, ch := range(chs) {
(gdb)
runtime.main () at /usr/local/go/src/runtime/proc.go:207
207 if atomic.Load(&runningPanicDefers) != 0 {
```
有疑问加站长微信联系(非本文作者)