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

边栏推荐
- [debug highlights] Expected input batch_size (1) to match target batch_size (0)
- Unity shader forge和自带的shader graph,有哪些优缺点?
- Knowledge Distillation 7: Detailed Explanation of Knowledge Distillation Code
- WeChat applet uses cloud functions to update and add cloud database nested array elements
- three.js make 3D photo album
- Safety 20220715
- 微软 AI 量化投资平台 Qlib 体验
- MySQL based operations
- Smartcom Programming Level 4 - Magic Academy Lesson 6
- Unity手机游戏性能优化系列:针对CPU端的性能调优
猜你喜欢

30 Years of Open Source Community | 2022 Open Atom Global Open Source Summit 30 Years of Open Source Community Special Event Held Successfully

产学研用 共建开源人才生态 | 2022开放原子全球开源峰会教育分论坛圆满召开

Win10 CUDA CUDNN installation configuration (torch paddlepaddle)

Learning DAVID Database (1)

(8) Math class, Arrays class, System class, Biglnteger and BigDecimal classes, date class

XSS靶场(三)prompt to win

Exsl file preview, word file preview web page method

Fusion Cloud Native, Empowering New Milestones | 2022 Open Atom Global Open Source Summit Cloud Native Sub-Forum Successfully Held
![[C language] Detailed explanation of operators](/img/fa/dce3da39f19b51c6d1b682128da36b.png)
[C language] Detailed explanation of operators

马斯克对话“虚拟版”马斯克,脑机交互技术离我们有多远
随机推荐
Heavyweight | The Open Atomic School Source Line activity was officially launched
PWN ROP
行业落地呈现新进展 | 2022开放原子全球开源峰会OpenAtom OpenHarmony分论坛圆满召开
[AUTOSAR-RTE]-5-Explicit (explicit) and Implicit (implicit) Sender-Receiver communication
扫雷游戏(c语言写)
从零开始,一镜到底,纯净系统搭建除草机(Grasscutter)
MySQL to revise the root password
打造基于ILRuntime热更新的组件化开发
MySQL database backup
马斯克对话“虚拟版”马斯克,脑机交互技术离我们有多远
Smartcom Programming Level 4 - Magic Academy Lesson 6
[C language] Detailed explanation of operators
Lua,ILRuntime, HybridCLR(wolong)/huatuo hot update comparative analysis
ERROR 1064 (42000) You have an error in your SQL syntax; check the manual that corresponds to your
Interview | Cheng Li, CTO of Alibaba: Cloud + open source together form a credible foundation for the digital world
Can't load /home/Iot/.rnd into RNG
微软 AI 量化投资平台 Qlib 体验
three.js make 3D photo album
【AUTOSAR-RTE】-4-Port and Interface and Data Type
Open Source Database Innovation in the Digital Economy Era | 2022 Open Atom Global Open Source Summit Database Sub-Forum Successfully Held