当前位置:网站首页>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)
}
}
}
}
边栏推荐
- Mobile number regular expression input box loses focus verification
- A review of small sample learning
- What is Ethernet and how to connect the computer
- [keil] GPIO output macro definition of aducm4050 official library
- CopyPlugin Invalid Options options should be array ValidationError: CopyPlugin Invalid Options
- Why does the SQL statement hit the index faster than it does not?
- Wechat applet new version prompt update
- For in JS Of and for in
- Deeply understand the characteristics of standard flow and off standard elements
- Laravel Aurora push
猜你喜欢
![[Huawei machine test] hj16 shopping list](/img/54/d28f5aea9350af7797ca7c069e564d.jpg)
[Huawei machine test] hj16 shopping list

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

ThinkPHP 5 log management

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

The article is on the list. Welcome to learn

Personalized Federated Learning with Moreau Envelopes
![H5 native player [learn video]](/img/51/83a200d0423b7274d1e981ec2ede2c.jpg)
H5 native player [learn video]

Kotlin compose perfect todo project surface rendering background and shadow

UVA816 Abbott’s Revenge

In Net 6 using dotnet format formatting code
随机推荐
投资理财产品的年限要如何选?
Database overview
Notes on non replacement elements in the line (padding, margin, and border)
滲透測試-提權專題
Characteristics of ES6 arrow function
Eyeshot Ultimate 2022 Crack By Xacker
Use js to simply implement the apply, call and bind methods
TX Text Control 30.0 ActiveX
HR took the initiative to raise the salary of the test lady. How did she do it?
Uva1103 ancient pictograph recognition
Student achievement management system based on SSH
Install pytorch through pip to solve the problem that torch cannot be used in jupyter notebook (modulenotfoundererror:no module named 'Torch').
Rce code execution & command execution (V)
For in JS Of and for in
Matlab notes
JS verification code input number auto skip
Opensea PHP development kit
CTFHUB SSRF
On Transform
Difference between asemi high power FET and triode