go context 了解 上下文

 

 

了解上下文 (go-rod.github.io)

https://go-rod.github.io/#/understand-context

 

在了解上下文之前,请确保您已学习 Goroutines 和 Channels。 上下文主要用于在 Goroutines 之间传输上下文信息,包括:取消信号、超时、截止时间、k-v 等。

例如,我们有一个每秒打印一次的长时间运行的函数:heartbeat  beat

 

package main

import (
    "fmt"
    "time"
)

func main() {
    heartbeat()
}

func heartbeat() {
    tick := time.Tick(time.Second)

    for {
        <-tick
        fmt.Println("beat")
    }
}

 

 

如果我们想在按回车键时中止心跳,我们可以像这样编码:

func main() {
    stop := make(chan struct{})
    go func() {
        fmt.Scanln()
        close(stop)
    }()

    heartbeat(stop)
}

func heartbeat(stop chan struct{}) {
    tick := time.Tick(time.Second)

    for {
        select {
        case <-tick:
        case <-stop:
            return
        }
        fmt.Println("beat")
    }
}

 

因为这种代码太常用了,所以 Golang 抽象出了一个辅助包来处理它, 它被称为上下文。 如果我们使用 Context,上面的代码将变成这样:

 

func main() {
    ctx, stop := context.WithCancel(context.Background())
    go func() {
        fmt.Scanln()
        stop()
    }()

    heartbeat(ctx)
}

func heartbeat(ctx context.Context) {
    tick := time.Tick(time.Second)

    for {
        select {
        case <-tick:
        case <-ctx.Done():
            return
        }
        fmt.Println("beat")
    }
}

 

posted @ 2023-02-02 16:11  AngDH  阅读(12)  评论(0编辑  收藏  举报