当前位置:网站首页>Go language study notes - dealing with timeout problems - Context usage | Go language from scratch
Go language study notes - dealing with timeout problems - Context usage | Go language from scratch
2022-07-31 04:45:00 【Swordsman ALiang_ALiang】
Study notes, where to write.
I recently looked at the use of the go language Context and found it very magical and convenient.
Speaking of context, when I was learning golang, I saw that many libraries were used. In short, context can handle the interaction between multiple goroutines.Similar to other languages, you may need to define a thread-safe object yourself, and use thread-safe objects to implement the interaction between multiple threads.Golang directly has a default package context, which can save the process of defining each time, which is very convenient.
I won't go into details about the use of Context, there are many online.
This article mainly uses context to implement the processing of a timeout scenario.
demo1
First use the context.WithTimeout method to implement timeout processing.
The code is as follows:
package mainimport ("context""fmt""time")func handle() {//build timeout context_ctx, _cancel := context.WithTimeout(context.Background(), 5*time.Second)go work(_ctx)time.Sleep(6 * time.Second)_cancel()}//Workfunc 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()}Code Description
1. Build a context with a 5-second timeout and pass it into the goroutine, and the work method polls the context status.
Execution results

demo2
First use the context.WithDeadline method to implement timeout processing.
The code is as follows:
package mainimport ("context""fmt""time")func handle1() {//build timeout context_ctx, _cancel := context.WithDeadline(context.Background(), time.Now().Add(5*time.Second))go work1(_ctx)time.Sleep(6 * time.Second)_cancel()}// job 1func 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()}Code Description
1. Pay attention to the time parameter method behind WithDeadline, which is different from WithTimeout.
2. Here, before the rotation training, judge whether the current time has exceeded the deadline, and if it exceeds, it will jump out directly.
Execution results

Summary
There are still many uses of context, which need to be used more in the project and share more feelings in the future.

边栏推荐
- 微信小程序使用云函数更新和添加云数据库嵌套数组元素
- ERP Production Operation Control Kingdee
- .NET-6.WinForm2.NanUI学习和总结
- 益智类游戏关卡设计:逆推法--巧解益智类游戏关卡设计
- Open Source Database Innovation in the Digital Economy Era | 2022 Open Atom Global Open Source Summit Database Sub-Forum Successfully Held
- Unity shader forge和自带的shader graph,有哪些优缺点?
- MySQL基础操作
- Musk talks to the "virtual version" of Musk, how far is the brain-computer interaction technology from us
- 【py脚本】批量二值化处理图像
- ERROR 1064 (42000) You have an error in your SQL syntax; check the manual that corresponds to your
猜你喜欢

Solved (the latest version of selenium framework element positioning error) NameError: name 'By' is not defined

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

ERROR 1064 (42000) You have an error in your SQL syntax; check the manual that corresponds to your

MySQL数据库必会的增删查改操作(CRUD)

Industry-university-research application to build an open source talent ecosystem | 2022 Open Atom Global Open Source Summit Education Sub-Forum was successfully held

Two address pools r2 are responsible for managing the address pool r1 is responsible for managing dhcp relays

PWN ROP

【云原生】DevOps(五):集成Harbor

VScode+ESP32 quickly install ESP-IDF plugin

MySQL数据库安装配置保姆级教程(以8.0.29为例)有手就行
随机推荐
Minesweeper game - C language
MySQL数据库增删改查(基础操作命令详解)
Lua,ILRuntime, HybridCLR(wolong)/huatuo热更新对比分析
Unity shader forge和自带的shader graph,有哪些优缺点?
exsl文件预览,word文件预览网页方法
The third is the code to achieve
BUG destroyer!!Practical debugging skills are super comprehensive
Unity框架设计系列:Unity 如何设计网络框架
MySQL数据库必会的增删查改操作(CRUD)
C language confession code?
Basic knowledge of mysql (2)
Safety 20220718
open failed: EACCES (Permission denied)
ENSP,划分VLAN、静态路由,三层交换机综合配置
PWN ROP
[debug highlights] Expected input batch_size (1) to match target batch_size (0)
Fusion Cloud Native, Empowering New Milestones | 2022 Open Atom Global Open Source Summit Cloud Native Sub-Forum Successfully Held
Two address pools r2 are responsible for managing the address pool r1 is responsible for managing dhcp relays
马斯克对话“虚拟版”马斯克,脑机交互技术离我们有多远
MySQL database backup