context withCancel 无法取消

weixin_38098470 2019-09-20 10:57:25
```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`
...全文
67 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
weixin_38112805 2019-09-20
  • 打赏
  • 举报
回复
将select中的 default去掉,因为有default的存在,在cancel还未执行的时候,select逻辑已经结束,走到下面的sleep,所以除非的就是sleep success,不是cancel了

433

社区成员

发帖
与我相关
我的任务
社区描述
其他技术讨论专区
其他 技术论坛(原bbs)
社区管理员
  • 其他技术讨论专区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧