登录
首页 >  Golang >  Go问答

能否终止未完成的 goroutine?

来源:stackoverflow

时间:2024-02-08 16:45:21 257浏览 收藏

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《能否终止未完成的 goroutine?》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!

问题内容

考虑一组检查工作,每个检查工作都有独立的逻辑,因此它们似乎很适合并发运行,例如:

type work struct {
    // ...
}

// this check could be quite time-consuming
func (w *work) check() bool {
    // return succeed or not

    //...
}

func checkall(works []*work) {
    num := len(works)
    results := make(chan bool, num)
    for _, w := range works {
        go func(w *work) {
            results <- w.check()
        }(w)
    }

    for i := 0; i < num; i++ {
        if r := <-results; !r {
            reportfailed()
            break;
        }
    }
}

func reportfailed() {
    // ...
}

当关心results时,如果逻辑是无论哪一项工作失败,我们断言所有工作都完全失败,通道中剩余的值是无用的。让剩余未完成的 goroutine 继续运行并将结果发送到通道是没有意义和浪费的,尤其是当 w.check() 相当耗时时。理想的效果类似于:

    for _, w := range works {
        if !w.Check() {
            ReportFailed()
            break;
        }
    }

这只运行必要的检查工作然后中断,但处于顺序非并发场景中。

那么,是否可以取消这些未完成的goroutines,或者发送到channel?


正确答案


取消(阻塞)发送

您最初的问题是询问如何取消发送操作。通道上的发送基本上是“即时”的。如果通道的缓冲区已满并且没有准备好的接收器,则通道上的发送将被阻塞。

可以使用 select 语句和您关闭的 cancel 通道“取消”此发送,例如:

cancel := make(chan struct{})

select {
case ch <- value:
case <- cancel:
}

在另一个 goroutine 上使用 close(cancel) 关闭 cancel 通道将使上述 select 放弃在 ch 上发送(如果它阻塞)。

但如上所述,发送是在“就绪”通道上“即时”进行的,并且发送首先评估要发送的值:

results <- w.check()

首先必须运行 w.check(),一旦完成,其返回值将发送到 results

取消函数调用

所以你真正需要的是取消 w.check() 方法调用。为此,惯用的方法是传递一个可以取消的 context.context 值,并且 w.check() 本身必须监视并“服从”此取消请求。

查看Terminating function execution if a context is cancelled

请注意,您的函数必须明确支持这一点。函数调用或 goroutine 没有隐式终止,请参阅 cancel a blocking operation in Go

所以你的 check() 应该看起来像这样:

// this check could be quite time-consuming
func (w *work) check(ctx context.context, workduration time.duration) bool {
    // do your thing and monitor the context!

    select {
    case <-ctx.done():
        return false
    case <-time.after(workduration): // simulate work
        return true
    case <-time.after(2500 * time.millisecond): // simulate failure after 2.5 sec
        return false
    }
}

checkall() 可能如下所示:

func checkall(works []*work) {
    ctx, cancel := context.withcancel(context.background())
    defer cancel()

    num := len(works)
    results := make(chan bool, num)

    wg := &sync.waitgroup{}
    for i, w := range works {
        workduration := time.second * time.duration(i)
        wg.add(1)
        go func(w *work) {
            defer wg.done()
            result := w.check(ctx, workduration)
            // you may check and return if context is cancelled
            // so result is surely not sent, i omitted it here.
            select {
            case results <- result:
            case <-ctx.done():
                return
            }
        }(w)
    }

    go func() {
        wg.wait()
        close(results) // this allows the for range over results to terminate
    }()

    for result := range results {
        fmt.println("result:", result)
        if !result {
            cancel()
            break
        }
    }
}

测试它:

checkall(make([]*work, 10))

输出(在 Go Playground 上尝试一下):

Result: true
Result: true
Result: true
Result: false

我们打印了 true 3 次(在 2.5 秒内完成),然后启动故障模拟,返回 false,并终止所有其他作业。

请注意,上面示例中的 sync.waitgroup 并不是严格需要的,因为 results 有一个能够保存所有结果的缓冲区,但总的来说,它仍然是一个很好的做法(如果您将来使用较小的缓冲区)。

查看相关内容:Close multiple goroutine if an error occurs in one in go

简短的回答是:

除非 goroutine 本身到达 return 或其堆栈末尾,否则您无法取消或关闭任何 goroutine。

如果您想取消某些操作,最好的方法是将 context.context 传递给它们,并在例程内监听此 context.done() 。每当上下文被取消时,你应该 return ,协程将在执行 defers(如果有)后自动死亡。

终于介绍完啦!小伙伴们,这篇关于《能否终止未完成的 goroutine?》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>