登录
首页 >  Golang >  Go问答

混淆了取消的背景

来源:stackoverflow

时间:2024-03-10 23:39:29 453浏览 收藏

本篇文章主要是结合我之前面试的各种经历和实战开发中遇到的问题解决经验整理的,希望这篇《混淆了取消的背景》对你有很大帮助!欢迎收藏,分享给更多的需要的朋友学习~

问题内容

package main

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

func myfunc(ctx context.context) {
    for {
        select {
        case <-ctx.done():
            fmt.printf("ctx is kicking in with error:%+v\n", ctx.err())
            return
        default:
            time.sleep(15 * time.second)
            fmt.printf("i was not canceled\n")
            return
        }
    }
}

func main() {
    ctx, cancel := context.withtimeout(
        context.background(),
        time.duration(3*time.second))
    defer cancel()

    var wg sync.waitgroup
    wg.add(1)
    go func() {
        defer wg.done()
        myfunc(ctx)
    }()

    wg.wait()
    fmt.printf("in main, ctx err is %+v\n", ctx.err())
}

我有上面的代码片段,可以像这样打印输出

I was not canceled
In main, ctx err is context deadline exceeded

Process finished with exit code 0

我知道 context 在 3 秒后超时,因此当我最终调用 ctx.err() 时,它确实给了我预期的错误。我还了解到,在我的 myfunc 中,一旦 selectdefault 的情况匹配,它就不会在 done 上匹配。我不明白的是,如何使用上下文逻辑使我的 go func myfunc 在 3 秒内中止。基本上,它不会在 3 秒内终止,所以我想了解 golang 的 ctx 如何帮助我解决这个问题?


解决方案


如果您想在上下文中使用超时和取消功能,那么在您的情况中需要同步处理 ctx.done() 。 p>

来自https://golang.org/pkg/context/#Context的解释

所以基本上 <-ctx.done() 将在两个条件下被调用:

  1. 当上下文超时超过
  2. 当上下文被强制取消时

当这种情况发生时,ctx.err() 将永远不会是 nil

我们可以对错误对象进行一些检查,看看上下文是否被强制取消或超过超时。

context包提供了两个错误对象,context.deadlineexceededcontext.timeout,这两个将帮助我们确定为什么调用<-ctx.done()

示例 #1 场景:强制取消上下文(通过 cancel()

在测试中,我们会尝试在超时之前取消上下文,以便执行 <-ctx.done()

ctx, cancel := context.withtimeout(
    context.background(),
    time.duration(3*time.second))

go func(ctx context.context) {
    // simulate a process that takes 2 second to complete
    time.sleep(2 * time.second)

    // cancel context by force, assuming the whole process is complete
    cancel()
}(ctx)

select {
case <-ctx.done():
    switch ctx.err() {
    case context.deadlineexceeded:
        fmt.println("context timeout exceeded")
    case context.canceled:
        fmt.println("context cancelled by force. whole process is complete")
    }
}

输出:

$ go run test.go 
context cancelled by force

示例 #2 场景:超出上下文超时

在这种情况下,我们使进程花费的时间比上下文超时时间长,因此理想情况下 <-ctx.done() 也将被执行。

ctx, cancel := context.withtimeout(
    context.background(),
    time.duration(3*time.second))

go func(ctx context.context) {
    // simulate a process that takes 4 second to complete
    time.sleep(4 * time.second)

    // cancel context by force, assuming the whole process is complete
    cancel()
}(ctx)

select {
case <-ctx.done():
    switch ctx.err() {
    case context.deadlineexceeded:
        fmt.println("context timeout exceeded")
    case context.canceled:
        fmt.println("context cancelled by force. whole process is complete")
    }
}

输出:

$ go run test.go 
context timeout exceeded

示例 #3 场景:由于发生错误而强制取消上下文

可能有一种情况,我们需要在进程中停止 goroutine,因为发生了错误。有时,我们可能需要在主例程中检索该错误对象。

为了实现这一点,我们需要一个额外的通道来将错误对象从 goroutine 传输到主例程中。

在下面的示例中,我准备了一个名为 cherr 的通道。每当(goroutine)进程中间发生错误时,我们将通过通道发送该错误对象,然后立即停止进程。

ctx, cancel := context.withtimeout(
    context.background(),
    time.duration(3*time.second))

cherr := make(chan error)

go func(ctx context.context) {
    // ... some process ...

    if err != nil {
        // cancel context by force, an error occurred
        cherr <- err
        return
    }

    // ... some other process ...

    // cancel context by force, assuming the whole process is complete
    cancel()
}(ctx)

select {
case <-ctx.done():
    switch ctx.err() {
    case context.deadlineexceeded:
        fmt.println("context timeout exceeded")
    case context.canceled:
        fmt.println("context cancelled by force. whole process is complete")
    }
case err := <-cherr:
    fmt.println("process fail causing by some error:", err.error())
}

其他信息 #1:在上下文初始化后立即调用 cancel()

根据 context documentation 关于 cancel() 函数的规定:

最好总是在上下文声明之后立即调用 cancel() 函数。它是否也在 goroutine 中被调用并不重要。这是为了确保当块内的整个过程完全完成时上下文始终被取消。

ctx, cancel := context.withtimeout(
    context.background(),
    time.duration(3*time.second))
defer cancel()

// ...

附加信息#2:goroutine 内的 defer cancel() 调用

您可以在 goroutine 中的 cancel() 语句上使用 defer(如果需要)。

// ...

go func(ctx context.Context) {
    defer cancel()

    // ...
}(ctx)

// ...

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

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