Description
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:
- Inapplicability for incomparable types. (sync/atomic: atomic.Value doesn't support CompareAndSwap #11260 (comment))
- Lack of concrete use-case. (sync/atomic: atomic.Value doesn't support CompareAndSwap #11260 (comment))
- Availability of
unsafe.Pointer
as an alternative. (sync/atomic: atomic.Value doesn't support CompareAndSwap #11260 (comment))
To address those points directly:
Swap
, unlikeCompareAndSwap
, does not require comparability. (Personally I think it would be good to addCompareAndSwap
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.)- I have identified a concrete use-case in the
crypto/tls
package. - According to @bradfitz in CL 41930,
unsafe.Pointer
is strongly discouraged outside of thesync
,runtime
, andreflect
packages.