Go Assembly by Example: Sync Atomic

This example is taken from the sync/atomic package which provides low-level atomic memory primitives. The swap operation, implemented by the SwapT functions, is the atomic equivalent of

  1. old = *addr
  2. *addr = new
  3. return old
  4. package atomic
  5. import (
  6. "unsafe"
  7. )

SwapInt32 atomically stores new into *addr and returns the previous *addr value.

  1. func SwapInt32(addr *int32, new int32) (old int32)
  2. #include "textflag.h"
  3. TEXT ·SwapInt32(SB),NOSPLIT,$0-20
  4. JMP ·SwapUint32(SB)
  5. TEXT ·SwapUint32(SB),NOSPLIT,$0-20
  6. MOVQ addr+0(FP), BP
  7. MOVL new+8(FP), AX

The XCHGL instruction is not vulnerable to a Write-After-Read as the bus is locked for the duration of the exchange.

  1. XCHGL AX, 0(BP)
  2. MOVL AX, old+16(FP)
  3. RET

Next example: Aes.

ft_authoradmin  ft_create_time2018-02-03 13:08
 ft_update_time2018-02-03 13:09