How does cancelCtx initialize its done property?

56 Views Asked by At

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. enter image description here

But at the stage of calling the cancel, done properly is turned into the chan struct{} enter image description here

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

1

There are 1 best solutions below

2
Paul Hankin On

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{}.