Skip to content

proposal: atomic: add (*Value).Swap #20164

Closed
@bcmills

Description

@bcmills

atomic.Value seems to be the preferred replacement for the atomic.*Pointer methods in code that avoids package unsafe. Unfortunately, atomic.Value doesn't support swaps, making it much less powerful than the equivalent Pointer methods.

When investigating sync.RWMutex usage in the standard library (#17973), I discovered an RWMutex in crypto/tls guarding two fields, sessionTicketKeys and originalConfig, that are always updated independently. It's trivial to replace sessionTicketKeys with an atomic.Value, but originalConfig needs an atomic swap.

More generally, it would be nice if atomic.Value were as complete a replacement as possible for unsafe.Pointer with atomic operations.


Adding CompareAndSwap was discussed previously (#11260).
The major arguments against at the time seem to have been:

  1. Inapplicability for incomparable types. (sync/atomic: atomic.Value doesn't support CompareAndSwap #11260 (comment))
  2. Lack of concrete use-case. (sync/atomic: atomic.Value doesn't support CompareAndSwap #11260 (comment))
  3. Availability of unsafe.Pointer as an alternative. (sync/atomic: atomic.Value doesn't support CompareAndSwap #11260 (comment))

To address those points directly:

  1. Swap, unlike CompareAndSwap, does not require comparability. (Personally I think it would be good to add CompareAndSwap too and simply panic for uncomparable types, but as I don't have a use-case for that I would prefer to keep it out-of-scope for this proposal.)
  2. I have identified a concrete use-case in the crypto/tls package.
  3. According to @bradfitz in CL 41930, unsafe.Pointer is strongly discouraged outside of the sync, runtime, and reflect packages.

(@dvyukov, @josharian, @OneOfOne, @cespare, @adg, @rsc)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions