当前位置:网站首页>Go语学习笔记 - 处理超时问题 - Context使用 从零开始Go语言
Go语学习笔记 - 处理超时问题 - Context使用 从零开始Go语言
2022-08-02 04:58:00 【m0_67400972】
学习笔记,写到哪是哪。
最近看了看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还有很多用法,需要在项目中多使用,以后分享更多感受。
先自我介绍一下,小编13年上师交大毕业,曾经在小公司待过,去过华为OPPO等大厂,18年进入阿里,直到现在。深知大多数初中级java工程师,想要升技能,往往是需要自己摸索成长或是报班学习,但对于培训机构动则近万元的学费,着实压力不小。自己不成体系的自学效率很低又漫长,而且容易碰到天花板技术停止不前。因此我收集了一份《java开发全套学习资料》送给大家,初衷也很简单,就是希望帮助到想自学又不知道该从何学起的朋友,同时减轻大家的负担。添加下方名片,即可获取全套学习资料哦
边栏推荐
- UE4 AI行为树实现随机和跟随移动
- [Digital IC hand-tear code] Verilog fixed priority arbiter | topic | principle | design | simulation
- 力扣练习——40 区间和的个数
- 系统(层次)聚类
- MySQL如何创建用户
- [QNX Hypervisor 2.2用户手册]9.20 vdev
- 选择黑盒测试用例设计方法的综合策略方案总结
- Does Conway's Law Matter for System Architecture?
- 力扣练习——38 分割回文串
- MySQL String Concatenation - Various String Concatenation Practical Cases
猜你喜欢
随机推荐
元宇宙:活在未来
Use the advanced timer of GD32F207 to generate hidden bugs in PWM waves
interrupt()、interrupted()和isInterrupted()你真的懂了吗
Mysql子查询关键字的使用(exists)
UE4 利用Mixamo自动绑骨并导入虚幻4
Matlab学习第二天
Live | 7.30 ApacheCon Asia 2022 IOT/IIOT topic, IoTDB PMC Qiao Jialin as the producer
How to quickly delete the compressed package password?
Centos7.9+mysql8.0开启指定IP远程连接数据库
MySQL如何对SQL做prepare预处理(解决IN查询SQL预处理仅能查询出一条记录的问题)
Luogu P2437 Bee Route
The practice of alibaba, data synchronization component canal
YOLOV5学习笔记(四)——项目目录及代码讲解
JDBC revisited
棋盘问题(DAY 94)
2022年7月学习计划完成情况
[Digital IC hand-tear code] Verilog fixed priority arbiter | topic | principle | design | simulation
2021年软件测试面试题大全
"Digital reconstruction of the system, getting the CEO is the first step"
mysql安装教程【安装版】