c++cthread-safetyint128

Is a 128 bit int written or loaded in two instructions in C/C++?


I know that there exists a int128_t type in C and C++.

If I have two threads one that is reading from a memory location containing this 128 bit integer and another that is writting to it.

Is there a chance that this value will be written as two 64 bit integer writes or will it be one 128 bit integer write?


Solution

  • The support is discussed in other answers. I'll discuss implementation issues.

    Usually when reading from memory, the compiler will emit processor instructions to fetch the data from memory into a register. This may be atomic depending on how the databus is set up between the processor and the memory.

    If your processor supports 128-bit transfers and the memory supports 128-bit data bus, this could be a single fetch (or write).

    If your processor supports 128-bit {register} transfers, but the data bus is smaller, the processor will perform enough fetches to transfer the data from memory. This may or may not be atomic, depending on your definition of atomic (it's one processor instruction, but may require more than one fetch).

    For processors that don't support 128-bit register transfers, the compiler will emit enough instructions to read the memory into register(s). This is for register to memory or memory to register transfers.

    For memory to memory transfers (e.g. variable assignments), the compiler may choose to use block reading and writing (if your processor has support for block reading and writing). Some processors support SIMD, others may have block transfer instructions. For example, the ARM has LDM (load multiple) and STM (store multiple) instructions for loading many registers from memory and storing many registers to memory. Another method of block reading and writing is to use a DMA device (if present). The DMA can transfer data while the processor executes other instructions. However, the overhead to use the DMA may require more instructions than using 16 8-byte (byte) transfers.

    In summary, compilers are not required to support int128_t. If they do support it, there are various methods to transfer the data, depending on the processor and platform hardware support. View the assembly language to see the instructions emitted by the compiler to support int128_t.