按道理 main 结束之前启动的 goroutine 不会结束,如果不发送 stopCh ,则会一直阻塞,为啥会提示有死锁
package main
import (
"fmt"
"sync"
"time"
)
var wg sync.WaitGroup
func main() {
fmt.Print("hello world\n")
ch1 := make(chan int)
ch2 := make(chan int)
stopCh := make(chan struct{})
wg.Add(1)
go work(ch1, ch2, stopCh)
ch1 <- 1
ch2 <- 1
time.Sleep(1000 * time.Millisecond)
// stopCh <- struct{}{}
var a int
wg.Wait()
fmt.Scan(&a)
}
func work(ch1, ch2 chan int, stopCh <-chan struct{}) {
defer wg.Done()
for {
select {
case <-stopCh:
return
case job1 := <-ch1:
fmt.Println("receive ch1 on first loop:", job1)
case job2 := <-ch2:
priority:
for {
select {
case job1 := <-ch1:
fmt.Println("receive ch1 on second loop:", job1)
default:
time.Sleep(1000 * time.Millisecond)
break priority
}
}
// 执行 job1 的内容
fmt.Println("receive ch2:", job2)
}
}
}
运行之后报错
hello world
receive ch1 on first loop: 1
receive ch2: 1
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [semacquire]:
sync.runtime_Semacquire(0xd77c28)
C:/go/src/runtime/sema.go:56 +0x49
sync.(*WaitGroup).Wait(0xd77c20)
C:/go/src/sync/waitgroup.go:130 +0x6b
main.main()
F:/code/go/c2c/client/client.go:24 +0x1b6
goroutine 6 [select]:
main.work(0xc000014180, 0xc0000141e0, 0xc000014240)
F:/code/go/c2c/client/client.go:30 +0x26e
created by main.main
F:/code/go/c2c/client/client.go:17 +0x146
exit status 2
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.