package mainimport ( "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 }}输出:doingstill doingcancel我不知道当它获得的上下文是取消时如何使这个 doSth 函数返回。换句话说,我希望这个函数的输出是:输出:doingcancel
1 回答

梦里花落0921
TA贡献1772条经验 获得超6个赞
您可以使用计时器,它将在给定的持续时间后通过通道发送消息。这允许您将其添加到选择中。
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")
}
}
- 1 回答
- 0 关注
- 120 浏览
添加回答
举报
0/150
提交
取消