go - 当 parent 返回时停止子 goroutine

标签 go goroutine

<分区>

我们有一个生成父 goroutine 的主 go 例程,父 goroutine 又生成一个子 go 例程。

即使在父 goroutine 返回后,子 goroutine 仍然运行。这会导致 goroutine 泄漏。

我们如何避免这种情况?

下面我添加了一个代码片段来模拟以下内容 这里的子 goroutine 可以是任何一个长时间运行的进程,比如数据库查询、api 调用等

Program output: 

In main function -  1
Starting parent function -  2
Starting child function -  3
Child timed out -  3
Completed parent -  2  // Implying that child goroutine is still running with main routine
package main

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

// WaitGroup used by main to wait for parent goroutine
var wg sync.WaitGroup

// Long duration process time
var duration = 100


func main() {
    fmt.Println("In main function - ", runtime.NumGoroutine())
    wg.Add(1)
    go parentRoutine()
    wg.Wait()
    fmt.Println("Completed parent - ", runtime.NumGoroutine())
}

func parentRoutine() {
    fmt.Println("Starting parent function - ", runtime.NumGoroutine())
    childRes := make(chan int)


        // Spawning child goroutine
    go func() {

               // Here the child is a simulation of a long running process which might take more time than expected timeout. It runs even after parent returns due to timeout


        fmt.Println("Starting child function - ", runtime.NumGoroutine())
        time.Sleep(time.Duration(duration)*time.Second)
        fmt.Println("Child ended - ", runtime.NumGoroutine())
        childRes <- 1
    }()

    select {
    case <-childRes:
        fmt.Println("Child completed - ", runtime.NumGoroutine())
    case <- time.After(time.Duration(3)*time.Second):
        fmt.Println("Child timed out - ", runtime.NumGoroutine())
    }
    wg.Done()
}

最佳答案

这是您的带上下文的代码段:https://play.golang.org/p/0TXyt4vuGKJ .

package main

import (
    "context"
    "fmt"
    "runtime"
    "sync"
    "time"
)

// WaitGroup used by main to wait for parent goroutine
var wg sync.WaitGroup

// Long duration process time
var duration = 100

func main() {
    fmt.Println("In main function - ", runtime.NumGoroutine())
    wg.Add(1)
    ctx, cancel := context.WithCancel(context.Background())
    go parentRoutine(ctx)
    wg.Wait()
    cancel()
    time.Sleep(time.Second) //If main immediately exists the child goroutine does not
                            //have the time to terminate.
    fmt.Println("Completed parent - ", runtime.NumGoroutine())
}

func parentRoutine(ctx context.Context) {
    fmt.Println("Starting parent function - ", runtime.NumGoroutine())
    childRes := make(chan int)

    // Spawning child goroutine
    go func(ctx context.Context) {

        // Here the child is a simulation of a long running process which might take more time than expected timeout. It runs even after parent returns due to timeout

        fmt.Println("Starting child function - ", runtime.NumGoroutine())
        select {
        case <-ctx.Done():
            fmt.Println("Child's context expired - ", runtime.NumGoroutine())
        case <-time.After(time.Duration(duration) * time.Second):
            //time consuming task
        }
        fmt.Println("Child ended - ", runtime.NumGoroutine())
        childRes <- 1
    }(ctx)

    select {
    case <-ctx.Done():
        fmt.Println("Parent's context expired - ", runtime.NumGoroutine())
    case <-childRes:
        fmt.Println("Child completed - ", runtime.NumGoroutine())
    case <-time.After(time.Duration(3) * time.Second):
        fmt.Println("Child timed out - ", runtime.NumGoroutine())
    }
    wg.Done()
}

现在输出如下:

In main function -  1
Starting parent function -  2
Starting child function -  3
Child timed out -  3
Child's context expired -  2
Child ended -  2
Completed parent -  2

关于go - 当 parent 返回时停止子 goroutine,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56224836/

相关文章:

go - gorm rest API 中的模式搜索

go - 如何在 goroutine 中返回值

go - 发送到 channel 的消息会丢失吗?

go - 如何使用 Sarama 在多个 goroutine 中消费 Kafka 主题?

在单独的 goroutine 中显示进度的 HTTP 服务器

go - 如何在Golang中的struct中访问嵌套字段

go - 尝试从Gitea连接到AD服务器时出错

戈兰 : panic before malloc heap initialized

go - sync.WaitGroup 没有像我预期的那样表现,我在这里缺少什么?

协程死锁?