From 0581d69dc6e67734293ba0c10b63df640a457aab Mon Sep 17 00:00:00 2001 From: Austin Clements Date: Thu, 21 Jul 2022 14:54:07 -0400 Subject: [PATCH] runtime/internal/atomic: add Pointer[T] type Change-Id: If8fcb37f4a8fcc0668af0df12f1cb8c66f2d2eea Reviewed-on: https://go-review.googlesource.com/c/go/+/418954 Run-TryBot: Austin Clements Reviewed-by: Michael Knyszek Reviewed-by: Michael Pratt TryBot-Result: Gopher Robot --- src/runtime/internal/atomic/types.go | 34 ++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/src/runtime/internal/atomic/types.go b/src/runtime/internal/atomic/types.go index d346a76b67..784acaadc1 100644 --- a/src/runtime/internal/atomic/types.go +++ b/src/runtime/internal/atomic/types.go @@ -414,6 +414,40 @@ func (u *UnsafePointer) CompareAndSwapNoWB(old, new unsafe.Pointer) bool { return Casp1(&u.value, old, new) } +// Pointer is an atomic pointer of type *T. +type Pointer[T any] struct { + u UnsafePointer +} + +// Load accesses and returns the value atomically. +func (p *Pointer[T]) Load() *T { + return (*T)(p.u.Load()) +} + +// StoreNoWB updates the value atomically. +// +// WARNING: As the name implies this operation does *not* +// perform a write barrier on value, and so this operation may +// hide pointers from the GC. Use with care and sparingly. +// It is safe to use with values not found in the Go heap. +func (p *Pointer[T]) StoreNoWB(value *T) { + p.u.StoreNoWB(unsafe.Pointer(value)) +} + +// CompareAndSwapNoWB atomically (with respect to other methods) +// compares u's value with old, and if they're equal, +// swaps u's value with new. +// +// Returns true if the operation succeeded. +// +// WARNING: As the name implies this operation does *not* +// perform a write barrier on value, and so this operation may +// hide pointers from the GC. Use with care and sparingly. +// It is safe to use with values not found in the Go heap. +func (p *Pointer[T]) CompareAndSwapNoWB(old, new *T) bool { + return p.u.CompareAndSwapNoWB(unsafe.Pointer(old), unsafe.Pointer(new)) +} + // noCopy may be embedded into structs which must not be copied // after the first use. // -- 2.50.0