Under the hood

The sync.Value type stores its data in a non-exported interface, as shown by the source code:

type Value struct {
    v interface{}
}

It uses a type of unsafe package to convert that structure into another one, which has the same data structure as an interface:

type ifaceWords struct {
typ unsafe.Pointer
data unsafe.Pointer
}

Two types with the same exact memory layout can be converted in this way, skipping the Go's type safety. This makes it possible to use atomic operations with the pointers and execute thread-safe Store and Load operations.

To get the lock for writing values, atomic.Value uses a compare and swap operation with the unsafe.Pointer(^uintptr(0)) value (which is 0xffffffff) in the type; it changes the value and replaces the type with the correct one. 

In the same way, the load operation loops until the type is different to 0xffffffff, before trying to read the value.

Using this expedient, atomic.Value is capable of storing and loading any value using other atomic operations.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.103.219