当前位置:   article > 正文

golang的context和chan 的使用

golang的context和chan 的使用

1. context 作用

context包的context的接口,主要是控制协程执行上下文的时间,以及取消程序的执行,以及上下文中传递数据等作用,golang中耗时或者需要协同的操作都会见到context的身影。

context有几个常用的方法

1.1 context.Backgroud()

创建一个空白的,顶级的,不会被取消的上下文。

1.2 context.WithTimeout

创建一个有执行时间限制的上下文
func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {
return WithDeadline(parent, time.Now().Add(timeout))
}
可以通过ctx.Done()方法获取上下超时的通知。

package main

import (
	"context"
	"fmt"
	"time"
)

func main() {
	parentCxt := context.Background()
	ctx, cancel := context.WithTimeout(parentCxt, time.Second*5)

	go longTimeTask(ctx)

	time.Sleep(time.Second * 10)
	cancel()
	fmt.Println("task cancel success")
}

func longTimeTask(ctx context.Context) {
	for {
		//fmt.Println("ok")
		select {
		case <-time.After(time.Second * 1):
			fmt.Println("task compete")
		case <-ctx.Done():
			fmt.Println("time out")
			return
		}
	}
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

1.3 context.WitchCancel(parentContext)

获取一个可以中止的上下文,该方法会返回一个新的context,和cancel函数,调用cancel函数后,通过ctx.Done()方法可以获取到上下文取消的通知

package main

import (
	"context"
	"fmt"
	"time"
)

func main() {
	parentCxt := context.Background()
	ctx, cancel := context.WithCancel(parentCxt)

	go longTimeTask(ctx)

	time.Sleep(time.Second * 10)
	cancel()
	fmt.Println("task cancel success")
}

func longTimeTask(ctx context.Context) {
	for {
		//fmt.Println("ok")
		select {
		case <-time.After(time.Second * 1):
			fmt.Println("task compete")
		case <-ctx.Done():
			fmt.Println("time out")
			return
		}
	}
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

1.4 context.WithValue()

func WithValue(parent Context, key, val any) Context {
if parent == nil {
panic(“cannot create context from nil parent”)
}
if key == nil {
panic(“nil key”)
}
if !reflectlite.TypeOf(key).Comparable() {
panic(“key is not comparable”)
}
return &valueCtx{parent, key, val}
}
可以在上下文中存贮一些参数,通过上下文随时获取。

2.chan 信道

golang的chan和map,切片,接口,函数一样是引用类型。
golang更加推荐使用chan去解决并发的协作的问题,对chan的读写是并发安全的,当然你也可也以使用sync.Mutex等包来控制并发。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/626985
推荐阅读
相关标签
  

闽ICP备14008679号