Go source code learning-sync.atomic library

The main functions in this package should be implemented at the bottom, not written in go, first look at the documentation.

The atomic package provides practical low-level atomic memory primitives to implement synchronization algorithms.

These functions require great care to be used correctly. Except for the special case of low-level applications, synchronization is best achieved using channels or other tools in the sync package. Share memory through communication; do not communicate through shared memory.

The swap operation implemented by the SwapT function is atomically equivalent to:

old = *addr
*addr = new
return old

That is, update the value of a memory address to a new value and return the old value

The comparison swap operation implemented by the CompareAndSwapT function is atomically equivalent to:

if *addr == old{
    *addr=new
    return true
}
return false

That is, the value of a memory address is compared with an old value, and if it is equal, it is updated to a new value and returns true, which means that the atomic update was successful, otherwise, it returns false to mean that the atomic update failed.

The addition operation implemented by the AddT function is atomically equivalent to:

*addr += dalte
return *addr

Load and store operations implemented by LoadT and StoreT are atomically equivalent to return *addrand *addr = val.

The following are the functions provided by the atomic package:

  1. Swap
  2. CompareAndSwap
  3. Add
  4. Load
  5. Store
    does not support Add. In addition, all operations support the following data types:
  • int32
  • int64
  • uint32
  • uint64
  • uintptr
  • unsafe.Pointer

If you want to subtract a signed negative constant value c from x, use AddUint32(&x, ^uint32(c-1)).


Look at value.go again

The Value structure provides atomic loading and storage for a fixed type of value. Load the zero value of Value to get nil. Once the stored function is called, the Value cannot be copied.

type Value struct {
    
    
	v interface{
    
    }
}

By calling LoadPointerand StorePointerachieve worthy loads and stores.

Guess you like

Origin blog.csdn.net/qq_35753140/article/details/104816141