如何确保goroutine在main()之前退出?不使用WaitGroup

如何确保goroutine在main()之前退出?不使用WaitGroup,go,channel,goroutine,Go,Channel,Goroutine,From的代码如下: package main import ( "fmt" "runtime" "time" ) var signal = make(chan struct{}) func printNumbers() { counter := 1 for { select { case <-signal: fmt.Print

From的代码如下:

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例程(之后)输出应为1


如何确保只有在其他go例程退出后才能退出go例程?

使用通道等待一个go例程很容易,如下所示。等待多个goroutine时使用WaitGroup

package main

import (
    "fmt"
    "runtime"
    "time"
)

var signal = make(chan struct{})
var done = make(chan struct{})   // closed when goroutine is done.

func printNumbers() {
    defer close(done)
    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
    <-done   // wait for the goroutine to be returning.
    fmt.Println("After: active go-routines", runtime.NumGoroutine())
    fmt.Println("Program exited")
}
主程序包
进口(
“fmt”
“运行时”
“时间”
)
var信号=make(chan结构{})
var done=make(chan struct{})//在goroutine完成时关闭。
func printNumber(){
延迟关闭(完成)
计数器:=1
为了{
挑选{
案例