【发布时间】:2021-01-27 05:59:21
【问题描述】:
来自以下代码:
package main
import (
"fmt"
"runtime"
"time"
)
var signal = make(chan struct{})
func printNumbers() {
counter := 1
for {
select {
case <-signal:
fmt.Println("Received signal")
// do some housekeeping
return
default:
time.Sleep(100 * time.Millisecond)
counter++
}
}
}
func main() {
go printNumbers()
fmt.Println("Before: active go-routines", runtime.NumGoroutine())
time.Sleep(time.Second)
close(signal)
//time.Sleep(1 * time.Second) do some work
fmt.Println("After: active go-routines", runtime.NumGoroutine())
fmt.Println("Program exited")
}
实际输出为:
Before: active go-routines 2
After: active go-routines 2
Program exited
Received signal
预期输出是:
Before: active go-routines 2
After: active go-routines 1
Program exited
Received signal
主要是活动的go-routines(after)输出应该是1
如何确保main() go-routine 仅在其他 go-routine 退出后才退出?
【问题讨论】: