大学网 > php中文网 > 后端开发Golang 函数如何使用上下文来取消并发任务?正文

Golang 函数如何使用上下文来取消并发任务?

中国大学网 2024-10-17

在 go 中,可以使用 context 包的 context.context 来取消并发任务,它提供了一种在 goroutine 之间传递取消信号的机制:创建 context.context:使用 context.background() 或 context.withcancel() 创建一个表示取消上下文的 context.context 对象。取消上下文:调用 context.withcancel() 返回的 cancelfunc 来取消上下文。传递上下文:将上下文传递给 goroutine,以便它们可以通过 context.done() 检查取消状态。实战案例:在 http 请求超时时优雅取消请求和关闭连接。

Go 中如何使用上下文取消并发任务

在 Go 中,context 包提供了一个机制,用于在不同的 goroutine 之间传递取消信号。这对于在超时或应用程序关闭时优雅地取消并发任务非常有用。

使用 context.Context

立即学习“go语言免费学习笔记(深入)”;

首先,创建一个代表取消上下文的 context.Context。这是通过调用 context.Background() 或 context.WithCancel() 完成的:

ctx := context.Background()

要取消上下文,请调用 CancelFunc,它由 context.WithCancel() 返回:

cancelFunc := context.WithCancel(ctx).CancelFunc

传递上下文

将上下文传递给 goroutine,以便它们可以检查取消状态:

go func() {
    for {
        select {
        case <-ctx.Done():
            // 上下文已取消,退出 goroutine
            return
        default:
            // 执行任务
        }
    }
}()

实战案例

考虑一个获取 HTTP 请求响应的 goroutine。如果请求在指定的时间量内没有完成,我们希望取消请求并关闭连接:

import (
    "context"
    "net/http"
)

func main() {
    // 创建带有 5 秒超时的上下文
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()

    // 创建一个 HTTP 请求
    req, err := http.NewRequest(http.MethodGet, "https://example.com", nil)
    if err != nil {
        log.Fatal(err)
    }

    // 添加 ctx 到请求
    req = req.WithContext(ctx)

    // 执行请求
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        if err == context.Canceled {
            // 请求被取消
            log.Println("请求已取消")
        } else {
            log.Fatal(err)
        }
    }
    defer resp.Body.Close()
}

以上就是Golang 函数如何使用上下文来取消并发任务?的详细内容,更多请关注中国大学网其它相关文章!