内存映射文件的原子操作

内存映射文件的原子操作

问题描述:

I'm using a memory mapped file and I need to use an atomic store on Go. I would use StoreUint64() if I were working on regularly allocated memory. However, I'm not sure how atomic operations work on memory mapped files.

Is it safe to use StoreUint64() on memory mapped files?

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

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

It's safe. For example, on amd64, it uses the XCHG instruction.

func StoreUint64

    func StoreUint64(addr *uint64, val uint64)

StoreUint64 atomically stores val into *addr.

src/sync/atomic/asm_amd64.s;

TEXT ·StoreUint64(SB),NOSPLIT,$0-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.