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
still doing
cancel
我不知道当它获得的上下文是取消时如何使这个 doSth 函数返回。
换句话说,我希望这个函数的输出是:
输出:
doing
cancel
梦里花落0921
相关分类