当前位置:网站首页>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还有很多用法,需要在项目中多使用,以后分享更多感受。
边栏推荐
- MySQL数据库增删改查(基础操作命令详解)
- MySQL基础操作
- npm、nrm两种方式查看源和切换镜像
- 微信小程序使用云函数更新和添加云数据库嵌套数组元素
- input输入框展示两位小数之precision
- 聚变云原生,赋能新里程 | 2022开放原子全球开源峰会云原生分论坛圆满召开
- Understanding and Using Unity2D Custom Scriptable Tiles (4) - Start to build a custom tile based on the Tile class (below)
- idea工程明明有依赖但是文件就是显示没有,Cannot resolve symbol ‘XXX‘
- 重磅 | 开放原子校源行活动正式启动
- WeChat applet uses cloud functions to update and add cloud database nested array elements
猜你喜欢
type_traits元编程库学习
WeChat applet uses cloud functions to update and add cloud database nested array elements
(5) final, abstract class, interface, inner class
BUG消灭者!!实用调试技巧超全整理
The idea project obviously has dependencies, but the file is not displayed, Cannot resolve symbol 'XXX'
Learning DAVID Database (1)
组件传值 provide/inject
Component pass value provide/inject
ENSP,划分VLAN、静态路由,三层交换机综合配置
Reinforcement learning: from entry to pit to shit
随机推荐
$parent/$children 与 ref
问题7:列表的拼接
(tree) Last Common Ancestor (LCA)
mysql基础知识(二)
[C language] General method for finding the sum of the greatest common factor and the least common multiple of two integers m and n, the classical solution
errno error code and meaning (Chinese)
IDEA common shortcut keys and plug-ins
"DeepJIT: An End-To-End Deep Learning Framework for Just-In-Time Defect Prediction" paper notes
MySQL database must add, delete, search and modify operations (CRUD)
Notes on the establishment of the company's official website (6): The public security record of the domain name is carried out and the record number is displayed at the bottom of the web page
errno错误码及含义(中文)
简易网络文件拷贝的C实现
$attrs/$listeners
开源汇智创未来 | 2022开放原子全球开源峰会OpenAtom openEuler分论坛圆满召开
log level and print log note
Redis counts new and retained users
(Line segment tree) Summary of common problems of basic line segment tree
Win10 CUDA CUDNN installation configuration (torch paddlepaddle)
VScode+ESP32 quickly install ESP-IDF plugin
MySQL based operations