当前位置:网站首页>Go Context - Cancelation and Propagation
Go Context - Cancelation and Propagation
2022-06-25 05:15:00 【Jornhitom】
import "context"!
view context package source code!
see example code for a server that uses contexts!
view golang documentation about context!
Suppose you need to make a sandwich , So you arranged for three people to buy tomatoes 、 Bread and ham . When the people who bought ham went to the supermarket, they found that there was no ham , So he asked the clerk of the supermarket to make a ham for him on the spot . The people who buy bread and tomatoes are on their way to the bakery and the tomato shop respectively .
Then you suddenly decide not to eat ham , In order not to waste resources , We need to have a mechanism , You can get ham makers to stop making ham , People who go to the supermarket immediately stop going to the supermarket , The people waiting for the ham immediately stopped waiting for the ham .
Customize a function sleepAndTalk() -
func sleepAndTalk(ctx context.Context, d time.Duration, msg string) {
select {
case <- time.After(d)
fmt.Println(msg)
case <- ctx.Done()
log.Print(ctx.Err())
}
}
Cancel -
func main() {
ctx := Context.Background()
ctx, cancel := context.WithCancel(ctx)
go func () {
s := bufio.NewScanner(os.Stdin)
s.Scan()
cancel()
}()
sleepAndTalk(ctx, 5 * time.Second, "Hello")
}
use go run *.go Run the above code , without Stdin, be 5 Second output Hello. If in 5 In seconds Stdin, You can immediately cancel Will run sleepAndTalk().
func main() {
ctx := Context.Background()
ctx, cancel := context.WithCancel(ctx)
go func () {
time.Sleep(time.Second)
cancel()
}()
sleepAndTalk(ctx, 5 * time.Second, "Hello")
}
Cancel() after 1 second. The code above is equivalent to -
func main() {
ctx := Context.Background()
ctx, cancel := context.WithCancel(ctx)
time.AfterFunc(time.Second, cancel)
sleepAndTalk(ctx, 5 * time.Second, "Hello")
}
or -
func main() {
ctx := Context.Background()
ctx, cancel := context.WithTimeout(ctx, time.Second)
cancel() // release resources for timer
sleepAndTalk(ctx, 5 * time.Second, "Hello")
}
Methods that handle cancelations -
Background()
WithCancel()
WithTimeout()
WithDeadline()
Use channels and select
func main() {
stop := make(chan bool)
go func() {
for {
select {
case <- stop: // stay channel After receiving the value, output stop And back to
fmt.Println("stop!")
return
default: // stay channel Received any bool I used to run all the time default
fmt.Println("running...")
time.Sleep(1 * time.Second)
}
}
}()
time.Sleep(5 * time.Second)
fmt.Println("sending value to channel \"stop\"")
stop <- true
time.Sleep(5 * time.Second)
}
Channels and selections can't handle complex thread trees .
Is the context OK ?
func main() {
// Background() is the root Context
// WithCancel() add a new Context node
ctx, cancel := context.WithCancel(context.Background())
go func() {
for {
select {
case <- ctx.Done(): // Done() In reference to cancel() After open the channel
fmt.Println("stop!")
return
default: // stay channel Received any bool I used to run all the time default
fmt.Println("running...")
time.Sleep(1 * time.Second)
}
}
}()
time.Sleep(5 * time.Second)
fmt.Println("sending value to channel \"stop\"")
cancel()
time.Sleep(5 * time.Second)
}
Examples of multiple threads -
func main() {
ctx, cancel := context.WithCancel(context.Background())
go worker(ctx, node1)
go worker(ctx, node2)
go worker(ctx, node3)
time.Sleep(5 * time.Second)
fmt.Println("sending value to channel \"stop\"")
cancel()
time.Sleep(5 * time.Second)
}
func worker(ctx context.Context, name string) {
go func() {
for {
select {
case <- ctx.Done(): // Done() In reference to cancel() After open the channel
fmt.Println(name, "stop!")
return
default: // stay channel Received any bool I used to run all the time default
fmt.Println(name, "running...")
time.Sleep(1 * time.Second)
}
}
}
}
边栏推荐
- Various pits encountered in the configuration of yolov3 on win10
- Personalized Federated Learning with Moreau Envelopes
- Database overview
- Drag modal box
- Dynamic programming full backpack
- CUDA compilation error
- How to download and use Xiaobai one click reload on the official website
- Two hours to take you into the software testing industry (with a full set of software testing learning routes)
- Array: force deduction dichotomy
- Laravel's little knowledge
猜你喜欢

Five simple data types of JS

Customize the console plot result style

Install pytorch through pip to solve the problem that torch cannot be used in jupyter notebook (modulenotfoundererror:no module named 'Torch').

基于SSH实现的学生成绩管理系统

Deeply understand the characteristics of standard flow and off standard elements

MySQL prevents Chinese garbled code and solves the problem of Chinese garbled code

EL & JSTL (XIII)

Detailed summary of flex layout

Flex flexible layout for mobile terminal page production

Go deep into the working principle of browser and JS engine (V8 engine as an example)
随机推荐
Create dynamic array
The construction and usage of wampserver framework
Dynamic programming full backpack
Could not find “store“ in the context of “Connect(homePage)
CUDA compilation error
Penetration test - directory traversal vulnerability
JS handwriting depth clone array and object
H5 canvas drawing circle drawing fillet [detailed explanation]
MySQL prevents Chinese garbled code and solves the problem of Chinese garbled code
Redis (17)
Object creation and invocation code example
Integrate CDN to create the ultimate service experience for customers!
Uva1103 ancient pictograph recognition
Mysql interactive_ Timeout and wait_ Timeout differences
Ctfhub eggs
February 19 CTF exercise
Svg code snippet of loading animation
Bind simulation, key points of interpreting bind handwritten code [details]
Conflict between v-mode and v-decorator in Ant Design
Professional things use professional people