当前位置:网站首页>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.
边栏推荐
- 扫雷小游戏——C语言
- MATLAB/Simulink & & STM32CubeMX tool chain completes model-based design development (MBD) (three)
- BUG消灭者!!实用调试技巧超全整理
- The Vue project connects to the MySQL database through node and implements addition, deletion, modification and query operations
- The idea project obviously has dependencies, but the file is not displayed, Cannot resolve symbol 'XXX'
- HCIP第十天_BGP路由汇总实验
- Create componentized development based on ILRuntime hot update
- 重磅 | 基金会为白金、黄金、白银捐赠人授牌
- 【py脚本】批量二值化处理图像
- Recursive implementation of the Tower of Hanoi problem
猜你喜欢
Interview | Cheng Li, CTO of Alibaba: Cloud + open source together form a credible foundation for the digital world
The idea project obviously has dependencies, but the file is not displayed, Cannot resolve symbol 'XXX'
论治理与创新 | 2022开放原子全球开源峰会OpenAnolis分论坛圆满召开
Unity打灵狐者
[C language] Detailed explanation of operators
MySQL数据库必会的增删查改操作(CRUD)
Solved (the latest version of selenium framework element positioning error) NameError: name 'By' is not defined
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
pom文件成橘红色未加载的解决方案
BUG消灭者!!实用调试技巧超全整理
随机推荐
HCIP Day 10_BGP Route Summary Experiment
【py脚本】批量二值化处理图像
扫雷游戏(c语言写)
简易网络文件拷贝的C实现
MySQL修改root账号密码
Gaussian distribution and its maximum likelihood estimation
C language confession code?
Lua,ILRuntime, HybridCLR(wolong)/huatuo hot update comparative analysis
Exsl file preview, word file preview web page method
MATLAB/Simulink & & STM32CubeMX tool chain completes model-based design development (MBD) (three)
BUG消灭者!!实用调试技巧超全整理
Hand in hand to realize the picture preview plug-in (3)
问题7:列表的拼接
【wpf】wpf中的那些模板之深度解析
开源社区三十年 | 2022开放原子全球开源峰会开源社区三十年专题活动圆满召开
The Vue project connects to the MySQL database through node and implements addition, deletion, modification and query operations
C语言表白代码?
PWN ROP
(5) final, abstract class, interface, inner class
ERROR 2003 (HY000) Can‘t connect to MySQL server on ‘localhost3306‘ (10061)解决办法