Skip to content

Instantly share code, notes, and snippets.

@lxfontes
Created November 26, 2019 18:49
Show Gist options
  • Save lxfontes/c15745f4ad9d605ab55be2a48952094e to your computer and use it in GitHub Desktop.
Save lxfontes/c15745f4ad9d605ab55be2a48952094e to your computer and use it in GitHub Desktop.
go atomic swappointer
package main
import (
"fmt"
"sync/atomic"
"unsafe"
)
type thing struct {
name string
}
type tracker struct {
pointer *thing
}
func main() {
xx := &thing{name: "ORIGINAL THING"}
yy := &thing{name: "ANOTHER THING"}
fmt.Printf("address for original %d, address for new %d\n", &xx, &yy)
t := &tracker{pointer: xx}
fmt.Printf("before: mem address %d, value %s\n", &t.pointer, t.pointer.name)
atomic.SwapPointer((*unsafe.Pointer)((unsafe.Pointer)(&t.pointer)), unsafe.Pointer(yy))
fmt.Printf("after: mem address %d, value %s\n", &t.pointer, t.pointer.name)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment