Skip to content

sync/atomic: add (*Value).Swap and (*Value).CompareAndSwap #39351

@carnott-snap

Description

@carnott-snap

Between a recent use case, and previous tickets (#11260, #20164, #26728), there is renewed interest in implementing Swap and CompareAndSwap for sync/atomic.Value.

The new interface serves to be more ergonomic, eschew the use of unsafe, and make atomic.Value have parity with the atomic.XxxPointer methods. There are some key differences between how the atomic.Value.XxxSwap and atomic.XxxSwapPointer work, e.g. panic on inconsistent types or nil, but these are fundamental to how atomic.Value works, and thus an accepted complexity.

Interface definition follows:

package atomic

// Swap stores new into Value and returns the previous value. It returns nil if
// the Value is empty.
//
// All calls to Swap for a given Value must use values of the same concrete
// type. Swap of an inconsistent type panics, as does Swap(nil).
func (v *Value) Swap(new interface{}) (old interface{})

// CompareAndSwapPointer executes the compare-and-swap operation for the Value.
//
// All calls to CompareAndSwap for a given Value must use values of the same
// concrete type. CompareAndSwap of an inconsistent type panics, as does
// CompareAndSwap(nil, old).
func (v *Value) CompareAndSwap(new, old interface{}) (swapped bool)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions