内存映射文件的原子操作

Atomic operations on memory mapped files

我正在使用内存映射文件,我需要在 Go 上使用原子存储。如果我处理定期分配的内存,我会使用 StoreUint64()。但是,我不确定原子操作如何在内存映射文件上工作。

在内存映射文件上使用 StoreUint64() 是否安全?

很安全。例如,在 amd64 上,它使用 XCHG 指令。

func StoreUint64

    func StoreUint64(addr *uint64, val uint64)

StoreUint64 atomically stores val into *addr.

src/sync/atomic/asm_amd64.s;

TEXT ·StoreUint64(SB),NOSPLIT,[=11=]-16
    MOVQ    addr+0(FP), BP
    MOVQ    val+8(FP), AX
    XCHGQ   AX, 0(BP)
    RET

Intel 64 and IA-32 Architectures Software Developer's Manual

XCHG—Exchange Register/Memory with Register

Description

Exchanges the contents of the destination (first) and source (second) operands. The operands can be two general-purpose registers or a register and a memory location. If a memory operand is referenced, the processor’s locking protocol is automatically implemented for the duration of the exchange operation, regardless of the presence or absence of the LOCK prefix or of the value of the IOPL.