Go context.WithCancel 的使用
Go context.WithCancel 的使用
下面为网友们详细介绍的教程内容,如有不对的地方欢迎指正!
WithCancel可以将一个Context包装为cancelCtx,并提供一个取消函数,调用这个取消函数,可以Cancel对应的Context
Go语言context包-cancelCtx[1]
疑问
context.WithCancel()取消机制的理解[2]
父母5s钟后出门,倒计时,父母在时要学习,父母一走就可以玩
package main
import (
"context"
"fmt"
"time"
)
func dosomething(ctx context.Context) {
for {
select {
case <-ctx.Done():
fmt.Println("playing")
return
default:
fmt.Println("I am working!")
time.Sleep(time.Second)
}
}
}
func main() {
ctx, cancelFunc := context.WithCancel(context.Background())
go func() {
time.Sleep(5 * time.Second)
cancelFunc()
}()
dosomething(ctx)
}

为什么调用cancelFunc就能从ctx.Done()里取得返回值? 进而取消对应的Context?
复习一下channel的一个特性
从一个已经关闭的channel里可以一直获取对应的零值

WithCancel代码分析
pkg.go.dev/context#WithCancel:[3]
// WithCancel returns a copy of parent with a new Done channel. The returned
// context's Done channel is closed when the returned cancel function is called
// or when the parent context's Done channel is closed, whichever happens first.
//
// Canceling this context releases resources associated with it, so code should
// call cancel as soon as the operations running in this Context complete.
//WithCancel 返回具有新 Done 通道的 parent 副本。 返回的上下文的完成通道在调用返回的取消函数或父上下文的完成通道关闭时关闭,以先发生者为准。
//取消此上下文会释放与其关联的资源,因此代码应在此上下文中运行的操作完成后立即调用取消。
func WithCancel(parent Context) (ctx Context, cancel CancelFunc) {
if parent == nil {
panic("cannot create context from nil parent")
}
c := newCancelCtx(parent) // 将parent作为父节点context 生成一个新的子节点
//获得“父Ctx路径”中可被取消的Ctx
//将child canceler加入该父Ctx的map中
propagateCancel(parent, &c)
return &c, func() { c.cancel(true, Canceled) }
}
WithCancel最后返回 子上下文和一个cancelFunc函数,而cancelFunc函数里调用了cancelCtx这个结构体的方法cancel
(代码基于go 1.16; 1.17有所改动)
// A cancelCtx can be canceled. When canceled, it also cancels any children
// that implement canceler.
type cancelCtx struct {
Context
mu sync.Mutex // protects following fields
done chan struct{} // created lazily, closed by first cancel call done是一个channel,用来 传递关闭信号
children map[canceler]struct{} // set to nil by the first cancel call children是一个map,存储了当前context节点下的子节点
err error // set to non-nil by the first cancel call err用于存储错误信息 表示任务结束的原因
}
相关阅读
-
开网站需要多少钱 公司网页制作流程及费用
一篇很详细的教程是关于开网站需要多少钱和公司网页制作流程及费用的相关经验,接下来IT袋带大家一起了解。 这个问题可以说是网站建设常见问题最热门的问题,也是客户咨询的最多的问
-
简单的网站设计模板 一个完整的网页设计流程
本文导读:简单的网站设计模板和一个完整的网页设计流程的电脑小知识,一起来看看吧! 随着个人创业的流行,很多个人也需要一个比较详细的网站来展示自己,开展个人业务,或者积累粉
-
哔哩哔哩是网站吗 哔哩哔哩是个什么网站
小编为你解答哔哩哔哩是个什么网站的IT小经验,哔哩哔哩是中国年轻世代高度聚集的文化社区和视频网站,简称B站,B站早期是一个ACG(动画、漫画、游戏)内容创作与分享的视频网站。
-
python工具有哪些 新手python编程入门自学知识
为大家分享python工具有哪些和新手python编程入门自学知识的介绍,如有不对的地方欢迎指正! 随着python的火热,不少的程序员业余时间都会研究这门编程语言。 利用python开发,大牛用vim,接了


