ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

go context 梳理

2022-02-10 21:02:08  阅读:134  来源: 互联网

标签:context ctx goruntine Background go favContextKey 梳理


context 是go的基础包

context 的使用场景:1. 控制关闭goruntine , 防止溢出  2. 定时完成goruntine  3. 带参数给 goruntine 

对应的有以下几种 context :

context.WithCancel
context.WithDeadline
context.WithTimeout
context.WithValue

 

context.Background() 用来 new 一个新 context
context.TODO()  用来 new 一个context 备用


类关系:

 

源码解析:
查看 go 源码或 看 http://www.codebaoku.com/godeep/goddeep-context-src.html

使用参照:
cancel:

gen := func(ctx context.Context) chan int {
		dst := make(chan int)
		n := 1
		go func() {
			fmt.Println("new go ")
			for {
				select {
				case <-ctx.Done():
					fmt.Println("goroutine over")
					return // return结束该goroutine,防止泄露
				case dst <- n:
					n++
				}
			}
		}()
		return dst
	}
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel() // 当我们取完需要的整数后调用cancel
	for n := range gen(ctx) {
		fmt.Println(n)
		if n == 5 {
			break
		}
	}

 

deadline / timeout

	d := time.Now().Add(50 * time.Millisecond)
	ctx, _ := context.WithDeadline(context.Background(), d)
	// ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
	// 尽管ctx会过期,但在任何情况下调用它的cancel函数都是很好的实践。
	// 如果不这样做,可能会使上下文及其父类存活的时间超过必要的时间。
	// defer cancel() 如果调用, 是主动停止(canceled) goruntine; 如果不调用 则是超时出 deadline exceeded
	go func() {
		select {
		case <-time.After(1 * time.Second):
			fmt.Println("sleep ")
		case <-ctx.Done():
			fmt.Println(ctx.Err())
			fmt.Println("over")
			return

		}
	}()

	time.Sleep(time.Second * 5)

  
contextval

	type favContextKey string // 定义一个key类型
	// f:一个从上下文中根据key取value的函数
	f := func(ctx context.Context, k favContextKey) {
		if v := ctx.Value(k); v != nil {
			fmt.Println("found value:", v)
			return
		}
		fmt.Println("key not found:", k)
	}
	k := favContextKey("language")
	// 创建一个携带key为k,value为"Go"的上下文
	// context.TODO()
	ctx := context.WithValue(context.Background(), k, "Go")
	f(ctx, k)
	f(ctx, favContextKey("color"))

  

 

标签:context,ctx,goruntine,Background,go,favContextKey,梳理
来源: https://www.cnblogs.com/xiaoxuebiye/p/15880771.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有