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

边栏推荐
- 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
- Recursive implementation of the Tower of Hanoi problem
- ClickHouse: Setting up remote connections
- PWN ROP
- WPF WPF 】 【 the depth resolution of the template
- 开放原子开源基金会秘书长孙文龙 | 凝心聚力,共拓开源
- MySQL数据库安装配置保姆级教程(以8.0.29为例)有手就行
- Vue项目通过node连接MySQL数据库并实现增删改查操作
- (5) final, abstract class, interface, inner class
- ERROR 1064 (42000) You have an error in your SQL syntax; check the manual that corresponds to your
猜你喜欢

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

ERROR 1819 (HY000) Your password does not satisfy the current policy requirements

行业落地呈现新进展 | 2022开放原子全球开源峰会OpenAtom OpenHarmony分论坛圆满召开

MATLAB/Simulink & & STM32CubeMX tool chain completes model-based design development (MBD) (three)

Unity手机游戏性能优化系列:针对CPU端的性能调优

C语言表白代码?

Open Source Smart Future | 2022 OpenAtom Global Open Source Summit OpenAtom openEuler sub-forum was successfully held

Reinforcement learning: from entry to pit to shit

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

MySQL database must add, delete, search and modify operations (CRUD)
随机推荐
【py脚本】批量二值化处理图像
Smartcom Programming Level 4 - Magic Academy Lesson 6
ABC D - Distinct Trio(k元组的个数
【debug锦集】Expected input batch_size (1) to match target batch_size (0)
扫雷游戏(c语言写)
[C language] General method of base conversion
three.js make 3D photo album
高等数学---第九章二重积分
The Vue project connects to the MySQL database through node and implements addition, deletion, modification and query operations
专访 | 阿里巴巴首席技术官程立:云+开源共同形成数字世界的可信基础
MySQL修改root账号密码
ERROR 1064 (42000) You have an error in your SQL syntax; check the manual that corresponds to your
Gaussian distribution and its maximum likelihood estimation
递归实现汉诺塔问题
.NET-6.WinForm2.NanUI学习和总结
BUG destroyer!!Practical debugging skills are super comprehensive
ERP生产作业控制 金蝶
【云原生】DevOps(五):集成Harbor
Musk talks to the "virtual version" of Musk, how far is the brain-computer interaction technology from us
强化学习:从入门到入坑再到拉屎