当前位置:网站首页>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)
}
}
}
}
边栏推荐
- Activereportsjs V3.0 comes on stage
- [keil] GPIO output macro definition of aducm4050 official library
- Personalized Federated Learning with Moreau Envelopes
- Database low-end SQL query statement fragment
- Essais de pénétration - sujets d'autorisation
- H5 native player [learn video]
- File upload vulnerability (III)
- Native JS high risk reminder pop-up code snippet, "are you sure you want to do this?" and "it cannot be recovered after deletion. Do you want to continue“
- How to download and use Xiaobai one click reload on the official website
- Google Earth engine (GEE) - Global jrc/gsw1_ 1 / batch download of yearlyhistory dataset (China region)
猜你喜欢

Penetration test - directory traversal vulnerability

CSRF (Cross Site Request Forgery) &ssrf (server request forgery) (IV)

buuctf(pwn)

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

Svg code snippet of loading animation

buuctf(re)

Deeply understand the characteristics of standard flow and off standard elements

The SQL response is slow. What are your troubleshooting ideas?

Example of dynamic programming 3 leetcode 55

渗透测试-目录遍历漏洞
随机推荐
Read the general components of antd source code
Swift rapid development
How to install the blue lake plug-in to support Photoshop CC 2017
The construction and usage of wampserver framework
Database low-end SQL query statement fragment
Various pits encountered in the configuration of yolov3 on win10
Penetration test - right raising topic
How to make colleagues under the same LAN connect to their own MySQL database
Array: force deduction dichotomy
PHP calls map API
epplus复制模板后打印区域变小的问题
SQL lab range explanation
Vue uses keep alive to cache page optimization projects
There is 404 in the laravel visit, except the home page is redirected; Index php
Kotlin compose perfect todo project surface rendering background and shadow
Response (XI)
parallel recovery slave next change & parallel recovery push change
A summary of the experiment of continue and break in C language
How to download and use Xiaobai one click reload on the official website
buuctf web