当前位置:网站首页>Golang context (context summary)
Golang context (context summary)
2022-06-13 01:17:00 【A simple heart】
1.context.WithCancel()
function : Returns an inherited Context, In parent process context Of Done When a function is closed, it closes its own Done passageway , Or after the following cancel After the function , Will close their own Done passageway . This closed channel can be used as a broadcast notification operation , Tell all context The related function stops the current work and returns directly . Generally, the usage scenario is used for the main collaboration process to control the exit of the child collaboration process , For one to many processing .
usage :
ctx,cancel := context.WithCancel(context.Background())
defer cancel()give an example : The main cooperative program control notifies the sub cooperative program to exit safely
package main
import (
"context"
"fmt"
"reflect"
"time"
)
func main() {
// Control the safe exit of the subprocess , call cancle after , Will close their own channels , Indicates the end of the program , All subprocesses will exit safely
ctx, cancle := context.WithCancel(context.Background())
defer cancle() // Cancel function context
go func() {
for {
select {
case <-ctx.Done():
return
default:
fmt.Println("go first ", reflect.TypeOf(ctx).Elem().Name())
}
time.Sleep(time.Second)
}
}()
go func() {
for {
select {
case <-ctx.Done():
return
default:
fmt.Println("go second ", reflect.TypeOf(ctx).Elem().Name())
}
time.Sleep(time.Second)
}
}()
go func() {
for {
select {
case <-ctx.Done():
return
default:
fmt.Println("go third ", reflect.TypeOf(ctx).Elem().Name())
}
time.Sleep(time.Second)
}
}()
fmt.Println("main-",reflect.TypeOf(ctx).Elem())
time.Sleep(5 * time.Second)
}Running results :
main- context.cancelCtx
go first cancelCtx
go second cancelCtx
go third cancelCtx
go third cancelCtx
go second cancelCtx
go first cancelCtx
go second cancelCtx
go first cancelCtx
go third cancelCtx
go third cancelCtx
go first cancelCtx
go second cancelCtx
go second cancelCtx
go third cancelCtx
go first cancelCtx
2.context.WithDeadline()
function : Pass a context , Waiting timeout , After a timeout , The timeout time will be returned , And will close context Of Done passageway , Other transmitted context, received Done Closed messages , Just go back . Similarly, the user notification message comes out .
usage :
ctx, cancle := context.WithDeadline(context.Background(), time.Now().Add(5*time.Second))
defer cancle()give an example :
package main
import (
"context"
"log"
"os"
"time"
)
var logg *log.Logger
func main() {
logg = log.New(os.Stdout, "", log.Ltime)
// Set a context , And set the corresponding timeout
ctx, cancle := context.WithDeadline(context.Background(), time.Now().Add(5*time.Second))
defer cancle()
go func() {
for {
select {
case <-ctx.Done():
logg.Printf("son go is end !")
return
}
}
}()
time.Sleep(8 * time.Second)
}
3.context.WithTimeout()
function : Pass a context , And set the corresponding timeout , call Deadline() Determine whether the current context has timed out
Also used for notification message processing , Control the processing of context .
usage :
// Define a timeout context , Specify the corresponding timeout
ctx, cancle := context.WithTimeout(context.Background(), 5*time.Second)
defer cancle()give an example :
package main
import (
"context"
"log"
"time"
)
func main() {
// Define a timeout context , Specify the corresponding timeout
ctx, cancle := context.WithTimeout(context.Background(), 5*time.Second)
defer cancle()
go func() {
for {
time.Sleep(1 * time.Second)
// Check ctx When will it time out
if deadline, ok := ctx.Deadline(); ok {
log.Print("deadline !", deadline)
// Judge whether the current time is ctx After the cancellation , Terminate the function directly , It is judged here that the hyperspace is cancelled ctx, You can exit and return directly .
if time.Now().After(deadline) {
log.Printf(ctx.Err().Error())
return
}
}
select {
case <-ctx.Done():
log.Print("done !")
// return // There is no such thing as , You can exit the function here
default:
log.Print("son !!!")
}
}
}()
time.Sleep(8 * time.Second)
}
Running results :
2021/06/16 20:02:48 deadline !2021-06-16 20:02:52.279309 +0800 CST m=+5.000190125
2021/06/16 20:02:48 son !!!
2021/06/16 20:02:49 deadline !2021-06-16 20:02:52.279309 +0800 CST m=+5.000190125
2021/06/16 20:02:49 son !!!
2021/06/16 20:02:50 deadline !2021-06-16 20:02:52.279309 +0800 CST m=+5.000190125
2021/06/16 20:02:50 son !!!
2021/06/16 20:02:51 deadline !2021-06-16 20:02:52.279309 +0800 CST m=+5.000190125
2021/06/16 20:02:51 son !!!
2021/06/16 20:02:52 deadline !2021-06-16 20:02:52.279309 +0800 CST m=+5.000190125
2021/06/16 20:02:52 After%!(EXTRA string=context deadline exceeded)
Use :<-ctx.Done(), End of Association
The operation results are as follows :
2021/06/16 20:06:54 deadline !2021-06-16 20:06:58.129238 +0800 CST m=+5.000237580
2021/06/16 20:06:54 son !!!
2021/06/16 20:06:55 deadline !2021-06-16 20:06:58.129238 +0800 CST m=+5.000237580
2021/06/16 20:06:55 son !!!
2021/06/16 20:06:56 deadline !2021-06-16 20:06:58.129238 +0800 CST m=+5.000237580
2021/06/16 20:06:56 son !!!
2021/06/16 20:06:57 deadline !2021-06-16 20:06:58.129238 +0800 CST m=+5.000237580
2021/06/16 20:06:57 son !!!
2021/06/16 20:06:58 deadline !2021-06-16 20:06:58.129238 +0800 CST m=+5.000237580
2021/06/16 20:06:58 done !
4.context.WithValue()
function : The user passes the message information of the context , Pass the message to be delivered from one collaboration process to another , Lead the context for relevant business processing .
usage :
// Set the corresponding message information k-v
ctx := context.WithValue(context.Background(), "trace_id", "888888")
ctx = context.WithValue(ctx, "session", 1)give an example :
package main
import (
"context"
"fmt"
"time"
)
func main() {
ctx := context.WithValue(context.Background(), "name", "eric")
ctx = context.WithValue(ctx, "session", 100001)
go func(ctx *context.Context) {
fmt.Println("start to go process")
// session
session, ok := (*ctx).Value("session").(int)
if ok {
fmt.Println(ok, "+", session)
}
name, ok := (*ctx).Value("name").(string)
if ok {
fmt.Println(ok, "+", name)
}
fmt.Println("end to go process")
}(&ctx)
// Let the main helper wait for the subprocess to exit , The main coordination process can be launched
time.Sleep(time.Second)
}
Running results :
start to go process
true + 100001
true + eric
end to go process
above context Summary of the use of context .
边栏推荐
- Et5.0 value type generation
- spiral matrix visit Search a 2D Matrix
- Matrix fast power
- np. Understanding of axis in concatenate
- [backtrader source code analysis 7] analysis of the functions for calculating mean value, variance and standard deviation in mathsupport in backtrader (with low gold content)
- How to choose stocks? Which indicator strategy is reliable? Quantitative analysis and comparison of strategic benefits of ASI, VR, arbr, DPO and trix indicators
- 刘徽与《九章算术》《海岛算经》简介
- 【斯坦福計網CS144項目】Lab1: StreamReassembler
- Pipeline流水线项目构建
- HashSet underlying source code
猜你喜欢

ES6 deconstruction assignment

Status of the thread

Simple operation of MySQL database

Create a simple game interface using pyGame

Minimum spanning tree problem

Jenkins持续集成操作

Liu Hui and introduction to nine chapter arithmetic and island arithmetic

Realization of flip animation
![[Latex] 插入图片](/img/0b/3304aaa03d3fea3ebb93b0348c3131.png)
[Latex] 插入图片

Undirected graph -- computing the degree of a node in compressed storage
随机推荐
Expression tree - medium order printout
软件测试的几种分类,一看就明了
ES6 deconstruction assignment
Key point detection data preparation and model design based on u-net Network -- detection model of four key points of industrial components
Traditional machine learning classification model predicts the rise and fall of stock prices under more than 40 indicators
Pipeline流水线项目构建
Memory learning book reference
使用Pygame创建一个简单游戏界面
Leetcode question brushing 03 stack
leetcode 142. Circular linked list II
Unity calls alertdialog
Wikipedia User Guide
How to print infinite symbol in WPS
Leetcode question brushing 07 double pointer
Leetcode-14- longest common prefix (simple)
Quick power explanation
Install pycharm process
刘徽与《九章算术》《海岛算经》简介
Web Application & applet application deployment
Alexnet实现Caltech101数据集图像分类(pytorch实现)