当前位置:网站首页>Go语学习笔记 - 处理超时问题 - Context使用 | 从零开始Go语言
Go语学习笔记 - 处理超时问题 - Context使用 | 从零开始Go语言
2022-07-31 04:28:00 【剑客阿良_ALiang】
学习笔记,写到哪是哪。
最近看了看go语言Context的使用,觉着很神奇也很便捷。
说到context,我在学习golang的时候看到很多库都用到了,简而言之,context可以处理多个goroutine之间的交互问题。类比于其他语言,你可能需要自己定义一个线程安全对象,通过线程安全对象来实现多个线程间的交互操作。golang直接有个默认包context,可以省掉每次定义的过程,还是很方便的。
具体关于Context的使用,我就不细说了,网上很多。
本文主要将我用context来实现一种超时场景的处理。
demo1
先使用context.WithTimeout方法来实现超时处理。
代码如下:
package main
import (
"context"
"fmt"
"time"
)
func handle() {
//构建超时上下文
_ctx, _cancel := context.WithTimeout(context.Background(), 5*time.Second)
go work(_ctx)
time.Sleep(6 * time.Second)
_cancel()
}
//工作
func work(ctx context.Context) {
for {
time.Sleep(1 * time.Second)
select {
case <-ctx.Done():
fmt.Println("work done")
default:
fmt.Println("working")
}
}
}
func main() {
handle()
}
代码说明
1、 构建一个5秒超时的上下文传入goroutine,work方法轮询上下文状态。
执行结果
demo2
先使用context.WithDeadline方法来实现超时处理。
代码如下:
package main
import (
"context"
"fmt"
"time"
)
func handle1() {
//构建超时上下文
_ctx, _cancel := context.WithDeadline(context.Background(), time.Now().Add(5*time.Second))
go work1(_ctx)
time.Sleep(6 * time.Second)
_cancel()
}
//工作1
func work1(ctx context.Context) {
for {
time.Sleep(1 * time.Second)
if _deadline, _a := ctx.Deadline(); _a {
if time.Now().After(_deadline) {
fmt.Println("after deadline")
break
}
}
select {
case <-ctx.Done():
fmt.Println("work done")
default:
fmt.Println("working")
}
}
}
func main() {
handle1()
}
代码说明
1、注意WithDeadline后面的时间参数方式,和WithTimeout不同。
2、这里在轮训前判断一下是否当前时间已经超过deadline,如果超过了直接跳出。
执行结果

小结
context还有很多用法,需要在项目中多使用,以后分享更多感受。

边栏推荐
- 两个地址池r2负责管地址池r1负责管dhcp中继
- Learning DAVID Database (1)
- 简易网络文件拷贝的C实现
- No qualifying bean of type question
- Hand in hand to realize the picture preview plug-in (3)
- Pytest e-commerce project combat (on)
- Pytest电商项目实战(上)
- IDEA common shortcut keys and plug-ins
- [C language] General method of base conversion
- $parent/$children and ref
猜你喜欢

【小土堆补充】Pytorch学习笔记_Anaconda虚拟环境使用

Unity打灵狐者

Learning DAVID Database (1)

Win10 CUDA CUDNN installation configuration (torch paddlepaddle)

(四)递归、可变参数、访问修饰符、理解 main 方法、代码块

已解决:不小心卸载pip后(手动安装pip的两种方式)

数字经济时代的开源数据库创新 | 2022开放原子全球开源峰会数据库分论坛圆满召开

Exsl file preview, word file preview web page method

binom二项分布,

BUG destroyer!!Practical debugging skills are super comprehensive
随机推荐
C# 实现PLC的定时器
pom文件成橘红色未加载的解决方案
Zotero如何删除自动生成的标签
binom二项分布,
open failed: EACCES (Permission denied)
Pytest e-commerce project combat (on)
volatile内存语义以及实现 -volatile写和读对普通变量的影响
端口排查步骤-7680端口分析-Dosvc服务
三子棋的代码实现
Hand in hand to realize the picture preview plug-in (3)
MATLAB/Simulink&&STM32CubeMX工具链完成基于模型的设计开发(MBD)(三)
Vue项目通过node连接MySQL数据库并实现增删改查操作
C language confession code?
log level and print log note
开源汇智创未来 | 2022开放原子全球开源峰会OpenAtom openEuler分论坛圆满召开
关于出现大量close_wait状态的理解
【论文阅读】Mastering the game of Go with deep neural networks and tree search
Redis uses sorted set to cache latest comments
Knowledge Distillation 7: Detailed Explanation of Knowledge Distillation Code
The third is the code to achieve