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()方法获取上下超时的通知。

go 复制代码
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.3 context.WitchCancel(parentContext)

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

go 复制代码
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.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等包来控制并发。

相关推荐
考虑考虑6 分钟前
UNION和UNION ALL的用法与区别
数据库·后端·mysql
sd213151219 分钟前
springboot3 spring security+jwt实现接口权限验证实现
java·后端·spring
m0_7482480224 分钟前
Spring Boot 集成 MyBatis 全面讲解
spring boot·后端·mybatis
qq_4476630524 分钟前
《Spring日志整合与注入技术:从入门到精通》
java·开发语言·后端·spring
源码姑娘26 分钟前
基于SpringBoot的智慧停车场小程序(源码+论文+部署教程)
spring boot·后端·小程序
蜡笔小新星30 分钟前
OpenCV中文路径图片读写终极指南(Python实现)
开发语言·人工智能·python·opencv·计算机视觉
Seven9735 分钟前
【设计模式】使用中介者模式实现松耦合设计
java·后端·设计模式
七七知享38 分钟前
2024 Qiniu 跨平台 Qt 高级开发全解析
开发语言·qt·零基础·操作系统·跨平台·qt5·精通
Seven9740 分钟前
【设计模式】探索状态模式在现代软件开发中的应用
java·后端·设计模式
Seven9741 分钟前
【设计模式】从事件驱动到即时更新:掌握观察者模式的核心技巧
java·后端·设计模式