浅谈Golang上下文Context

简介: 浅谈Golang上下文Context

Context

前言

Golang底层原理剖析之上下文Context


  1. context 主要用来在 goroutine 之间传递上下文信息 - 取消信号、超时时间、截止时间、k-v 等
  2. Context上下文 - 结合Linux操作系统的CPU上下文切换/子进程与父进程进行理解
  3. 如何优雅地使用context - 与select配合使用,管理协程的生命周期
  4. Context的底层实现是什么? - mutex与channel的结合,前者用于初始部分参数,后者用于通信


代码

package main
import (
  "context"
  "fmt"
  "time"
)
// Tip: 通过 cancel 主动关闭
func ctxCancel() {
  ctx, cancel := context.WithCancel(context.Background())
  go func(ctx context.Context) {
    select {
    case <-ctx.Done():
      fmt.Println(ctx.Err())
    case <-time.After(time.Millisecond * 100):
      fmt.Println("Time out")
    }
  }(ctx)
  cancel() //外部调用cancel(),其ctx.Done()将会接收到channel信息
}
// Tip: 通过超时,自动触发
func ctxTimeout() {
  ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*10) //10毫秒后会自动触发
  // 主动执行cancel,也会让协程收到消息
  defer cancel()
  go func(ctx context.Context) {
    select {
    case <-ctx.Done():
      fmt.Println(ctx.Err())
    case <-time.After(time.Millisecond * 100):
      fmt.Println("Time out")
    }
  }(ctx)
  time.Sleep(time.Second)
}
// Tip: 通过设置截止时间,触发time out
func ctxDeadline() {
  ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(10*time.Millisecond))
  defer cancel()
  go func(ctx context.Context) {
    select {
    case <-ctx.Done():
      fmt.Println(ctx.Err())
    case <-time.After(time.Millisecond * 100):
      fmt.Println("Time out")
    }
  }(ctx)
  time.Sleep(time.Second)
}
// Tip: 用Key/Value传递参数,可以浅浅封装一层,转化为自己想要的结构体
func ctxValue() {
  ctx := context.WithValue(context.Background(), "user", "wxf")
  go func(ctx context.Context) {
    v, ok := ctx.Value("user").(string)
    if ok {
      fmt.Println("pass user value", v)
    }
  }(ctx)
  time.Sleep(time.Second)
}

注意点

子节点覆盖父节点数据的情况


最好不要直接使用stirng,int这种基础类型作为key,而是用自定义类型包装一下



valueCtx通过context形成了一个链表结构,不过需要注意,context本身是本着不可改变的模式设计的,所以不要试图修改ctx里面保存的值


目录
相关文章
|
9月前
|
存储 SQL 安全
Golang底层原理剖析之上下文Context
Golang底层原理剖析之上下文Context
173 0
|
6月前
|
人工智能 Go
Golang 里的 context
Golang 里的 context
38 0
|
监控 安全 Go
Golang 语言中 Context 的使用方式
Golang 语言中 Context 的使用方式
63 0
|
9月前
|
数据管理 Go 开发者
Golang深入浅出之-Go语言上下文(context)包:处理取消与超时
【4月更文挑战第25天】Go语言中的`context`包在并发、网络请求和长任务中至关重要,提供取消、截止时间和元数据管理。本文探讨`context`基础,如`Background()`、`TODO()`、`WithCancel()`、`WithDeadline()`和`WithTimeout()`。常见问题包括不当传递、过度使用`Background()`和`TODO()`以及忽略错误处理。通过取消和超时示例,强调正确传递上下文、处理取消错误和设置超时以提高应用健壮性和响应性。正确使用`context`是构建稳定高效Go应用的关键。
171 1
|
9月前
|
Go 开发者
Golang深入浅出之-Go语言上下文(context)包:处理取消与超时
【4月更文挑战第23天】Go语言的`context`包提供`Context`接口用于处理任务取消、超时和截止日期。通过传递`Context`对象,开发者能轻松实现复杂控制流。本文解析`context`包特性,讨论常见问题和解决方案,并给出代码示例。关键点包括:1) 确保将`Context`传递给所有相关任务;2) 根据需求选择适当的`Context`创建函数;3) 定期检查`Done()`通道以响应取消请求。正确使用`context`包能提升Go程序的控制流管理效率。
88 1
|
9月前
|
监控 安全 Go
golang面试:golang中的context(四)
golang面试:golang中的context(四)
88 0
|
存储 SQL 安全
Golang 语言标准库 context 包控制 goroutine
Golang 语言标准库 context 包控制 goroutine
64 0
|
Go API 调度
No.14 Golang中Context你了解吗?(下)
No.14 Golang中Context你了解吗?
|
5月前
|
Go
Golang语言之管道channel快速入门篇
这篇文章是关于Go语言中管道(channel)的快速入门教程,涵盖了管道的基本使用、有缓冲和无缓冲管道的区别、管道的关闭、遍历、协程和管道的协同工作、单向通道的使用以及select多路复用的详细案例和解释。
177 4
Golang语言之管道channel快速入门篇
|
5月前
|
Go
Golang语言文件操作快速入门篇
这篇文章是关于Go语言文件操作快速入门的教程,涵盖了文件的读取、写入、复制操作以及使用标准库中的ioutil、bufio、os等包进行文件操作的详细案例。
88 4
Golang语言文件操作快速入门篇