golang 的 context.Context

Context 包含 Deadlines, cancelation signals, 和 other request-scoped values 贯穿不同的API和go线程. Context 一般会组织成一个树形结构,每一个Context的实现对应一个线程或者多个线程。Context 树可能的形式如下:

这里写图片描述

定义

type Context interface {
        Deadline() (deadline time.Time, ok bool)
        Done() <-chan struct{}
        Err() error
        Value(key interface{}) interface{}
}

其中 Deadline 就是需要确认什么时间结束这个Context。在结束这个Context的信号被捕获,会通过channel Done() 的值知道本个Context树已经退出。这时能够通过 Err() 的输出信息获知退出的原因。

Value(),可以通过一个Key获取到一个Value。此功能有点类似于一个会话的各种属性。在不同的函数中能够共用这个属性。

用法

1.结束 Context 树,这里就要说到如何生成Context节点。

最高层的Context就是用一个空的Context来替代的,也就是根Context是空的。生成方法如下:

ctx := context.Background()

接下来生成根节点的子节点,这里可以选择集中方法:

  • 通过cancel函数来结束Context
// calling cancel will stop the ctxA
ctxA, cancel := context.WithCancel(ctx)
  • 通过 结束时间 结束 Context

    // deadline is New() + 50 millisecond
    d := time.Now().Add(50 * time.Millisecond)
    // either calling cancel or reaching the deadline will stop the ctxA
    ctxA, cancel := context.WithDeadline(ctx, d)
  • 通过超时时间结束 Context

    // either calling cancel or timeout will stop the ctxA
    ctxA, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)

2.获取Context中的存储的共享值。

这个共享值的方法生成 Context 树是没有停掉自己的 Context 方法。它可以通过上层的Contex的停止使得自己停止。

ctxA := context.WithValue(ctx, "language", "Go")
// v is "Go"
v := ctxA.Value("language")

文末,拷贝官网的例子有助于理解。

package main

import (
    "context"
    "fmt"
)

func main() {
    // gen generates integers in a separate goroutine and
    // sends them to the returned channel.
    // The callers of gen need to cancel the context once
    // they are done consuming generated integers not to leak
    // the internal goroutine started by gen.
    gen := func(ctx context.Context) <-chan int {
        dst := make(chan int)
        n := 1
        go func() {
            for {
                select {
                case <-ctx.Done():
                    return // returning not to leak the goroutine
                case dst <- n:
                    n++

                }
            }

        }()
        return dst
    }

    ctx, cancel := context.WithCancel(context.Background())
    defer cancel() // cancel when we are finished consuming integers

    for n := range gen(ctx) {
        fmt.Println(n)
        if n == 5 {
            break
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值