```go
package main
import (
"context"
"fmt"
"time"
)
func sleep(ctx context.Context, d time.Duration) error {
select {
case <-ctx.Done():
return context.Canceled
default:
}
time.Sleep(d)
return nil
}
var cancelFunc context.CancelFunc
func main() {
go func() {
parent := context.Background()
ctx, cancel := context.WithCancel(parent)
cancelFunc = cancel
select {
case <-ctx.Done():
fmt.Println("canceled")
return
default:
}
err := sleep(ctx, 2*time.Second)
if err != nil {
fmt.Println(err.Error())
return
}
fmt.Println("sleep success")
}()
time.Sleep(time.Second)
go func() {
cancelFunc()
}()
time.Sleep(2 * time.Second)
}
```
返回的是 `sleep success` 而不是 `canceled, context canceled`
有疑问加站长微信联系(非本文作者)