当前位置:网站首页>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.

边栏推荐
- Interview | Cheng Li, CTO of Alibaba: Cloud + open source together form a credible foundation for the digital world
- ENSP,划分VLAN、静态路由,三层交换机综合配置
- [C language] General method of base conversion
- MATLAB/Simulink & & STM32CubeMX tool chain completes model-based design development (MBD) (three)
- unity2d game
- 已解决(最新版selenium框架元素定位报错)NameError: name ‘By‘ is not defined
- 问题7:列表的拼接
- Solved (the latest version of selenium framework element positioning error) NameError: name 'By' is not defined
- Understanding of the presence of a large number of close_wait states
- 【R语言】【3】apply,tapply,lapply,sapply,mapply与par函数相关参数
猜你喜欢

View source and switch mirrors in two ways: npm and nrm

The input input box displays the precision of two decimal places

Unity打灵狐者

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

(5) final, abstract class, interface, inner class

Error EPERM operation not permitted, mkdir ‘Dsoftwarenodejsnode_cache_cacach两种解决办法

prompt.ml/15中<svg>标签使用解释

从零开始,一镜到底,纯净系统搭建除草机(Grasscutter)

ERROR 2003 (HY000) Can‘t connect to MySQL server on ‘localhost3306‘ (10061)

Learning DAVID Database (1)
随机推荐
Error EPERM operation not permitted, mkdir ‘Dsoftwarenodejsnode_cache_cacach两种解决办法
Unity Tutorial: URP Rendering Pipeline Practical Tutorial Series [1]
C Implementation of Simple Network File Copy
The MySQL database installed configuration nanny level tutorial for 8.0.29 (for example) have hands
C language confession code?
[Linear Neural Network] softmax regression
On Governance and Innovation | 2022 OpenAtom Global Open Source Summit OpenAnolis sub-forum was successfully held
Doris学习笔记之监控
Win10 CUDA CUDNN 安装配置(torch paddlepaddle)
Safety 20220718
PWN ROP
ERROR 1064 (42000) You have an error in your SQL syntax; check the manual that corresponds to your
HCIP Day 10_BGP Route Summary Experiment
exsl文件预览,word文件预览网页方法
重磅 | 开放原子校源行活动正式启动
ClickHouse: Setting up remote connections
关于出现大量close_wait状态的理解
扫雷游戏(c语言写)
STM32HAL库修改Hal_Delay为us级延时
unity2d game