How to use Atomic Pointers in Golang 1.19

“Atomic” in computer programming refers to performing operations one at a time. Objective-C has atomic properties. It ensures a safe reading and writing to a property from different threads. In Objective-C, it is used with immutable types. This is because immutable types are really “recreated” to change it. In other words, changing an immutable type in your code will not cause the compiler to throw an error. However, it’ll instantiate a new object when you do so. A prime example is Go’s append function, it makes a new array for each invocation. In Obj-C, atomic properties will ensure operations are performed one after another to prevent threads from accessing a memory address simultaneously. Since Go is multithreaded, it supports atomic operations as well. Golang 1.19 introduces new atomic types. My favorite addition is atomic.Pointer , it provides a sleek alternative to atomic.Value . It’s also a great showcase of how generics enhance the developer experience.

The Go 1.19 atomic.Pointer

atomic.Pointer is a generic type. Unlike Value , it does not require asserting your stored value to access it. Here is a code block that defines and stores a pointer :

package mainimport (
)type ServerConn struct {
Connection net.Conn
ID string
Open bool
}func main() {
p := atomic.Pointer[ServerConn]{} s := ServerConn{ ID : "first_conn"}
p.Store( &s ) fmt.Println(p.Load()) // Will display value stored.

I instantiate variable pas a struct literal. I then proceed to store the pointer of the variable s in p , s represents a server connection. Voila, we’ve passed the first step toward atomicity. By storing the variable as an atomic value, we’ll ensure that there is no simultaneous access to the memory address. For example, maps will cause a program to panic if it is read and written simultaneously. As are atomic operations, locks are a great way to prevent these panics.

Golang Atomic Pointer use cases