```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`
将select中的 default去掉,因为有default的存在,在cancel还未执行的时候,select逻辑已经结束,走到下面的sleep,所以除非的就是sleep success,不是cancel了
#1