英文:
How to return at once in function when the context is cancel in GoLang?
问题
package main
import (
"context"
"fmt"
"time"
)
func main() {
ctx := context.Background()
c, fn := context.WithCancel(ctx)
go doSth(c)
time.Sleep(1 * time.Second)
fn()
time.Sleep(10 * time.Second)
}
func doSth(ctx context.Context) {
fmt.Println("doing")
time.Sleep(2 * time.Second)
fmt.Println("still doing")
select {
case <-ctx.Done():
fmt.Println("cancel")
return
}
}
输出:
doing
cancel
我不知道如何使这个doSth
函数在接收到取消的上下文时返回。
换句话说,我希望这个函数的输出是:
输出:
doing
cancel
英文:
package main
import (
"context"
"fmt"
"time"
)
func main() {
ctx := context.Background()
c, fn := context.WithCancel(ctx)
go doSth(c)
time.Sleep(1 * time.Second)
fn()
time.Sleep(10 * time.Second)
}
func doSth(ctx context.Context) {
fmt.Println("doing")
time.Sleep(2 * time.Second)
fmt.Println("still doing")
select {
case <-ctx.Done():
fmt.Println("cancel")
return
}
}
OUTPUT:
doing
still doing
cancel
I don't know how to make this doSth function return when the context it get is canncel.
In another word, I want the output of this function is:
OUTPUT:
doing
cancel
答案1
得分: 0
你可以使用一个定时器,在给定的时间后通过一个通道发送一条消息。这样可以将其添加到select语句中。
func main() {
ctx := context.Background()
c, fn := context.WithCancel(ctx)
go doSth(c)
time.Sleep(1 * time.Second)
fn()
time.Sleep(10 * time.Second)
}
func doSth(ctx context.Context) {
fmt.Println("doing")
timer := time.NewTimer(2 * time.Second)
select {
case <-timer.C:
fmt.Println("still doing")
case <-ctx.Done():
fmt.Println("cancel")
}
}
英文:
You can use a timer, which will send a message over a channel after the given duration. This allows you to add it in the select.
func main() {
ctx := context.Background()
c, fn := context.WithCancel(ctx)
go doSth(c)
time.Sleep(1 * time.Second)
fn()
time.Sleep(10 * time.Second)
}
func doSth(ctx context.Context) {
fmt.Println("doing")
timer := time.NewTimer(2 * time.Second)
select {
case <-timer.C:
fmt.Println("still doing")
case <-ctx.Done():
fmt.Println("cancel")
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论