cancelCtx如何初始化其done属性?

huangapple go评论81阅读模式
英文:

How does cancelCtx initialize its done property?

问题

有人知道Go语言中的上下文背景是如何工作的吗?

我看到通过调用WithCancel函数,会调用newCancelCtx函数。

func WithCancel(parent Context) (ctx Context, cancel CancelFunc) {
	if parent == nil {
		panic("cannot create context from nil parent")
	}
	c := newCancelCtx(parent)
	propagateCancel(parent, &c)
	return &c, func() { c.cancel(true, Canceled) }
}

// newCancelCtx返回一个初始化的cancelCtx。
func newCancelCtx(parent Context) cancelCtx {
	return cancelCtx{Context: parent}
}

newCancelCtx函数中,cancelCtx结构体被初始化并返回。

在cancelCtx结构体中,done属性只是一个atomic.Value类型的实例。

但是在调用cancel函数的阶段,done属性被转换为chan struct{}类型。

所以我的问题是,cancelCtx中的done属性是如何从atomic.Value转换为chan struct{}的?

英文:

Does anybody knows how does context underlying works in Go?

I see that by calling WithCancel, new CancelCtx will be called

func WithCancel(parent Context) (ctx Context, cancel CancelFunc) {
	if parent == nil {
		panic("cannot create context from nil parent")
	}
	c := newCancelCtx(parent)
	propagateCancel(parent, &c)
	return &c, func() { c.cancel(true, Canceled) }
}

// newCancelCtx returns an initialized cancelCtx.
func newCancelCtx(parent Context) cancelCtx {
	return cancelCtx{Context: parent}
}

And in the newCancelCtx, cancelCtx construct is initialized and returned.

In the cancelCtx, the done property is just an instance from type of atomic.Value.
cancelCtx如何初始化其done属性?

But at the stage of calling the cancel, done properly is turned into the chan struct{}
cancelCtx如何初始化其done属性?

So my question is how is done property in cancelCtx converted from atomic.Value to chan struct{}?

答案1

得分: 2

ctx.doneatomic.Value中保存了一个chan struct{}

在你提供的代码中,你可以看到上下文代码是如何提取通道的:

d, _ := c.done.Load().(chan struct{})

c.done.Load()检索存储在atomic.Value中的值(如果有的话),然后将其类型断言为chan struct{}

英文:

ctx.done holds a chan struct{} in the atomic.Value.

In the code you included a picture of, you can see how the context code extracts the channel:

d, _ := c.done.Load().(chan struct{})

c.done.Load() retrieves the value (if any) stored in the atomic.Value (which has any type), and then type-asserts it to chan struct{}.

huangapple
  • 本文由 发表于 2023年2月25日 14:39:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75563730.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定