none
Are 32-bit reads / writes thread-safe on SMP systems? RRS feed

  • Question

  • I know that reading and writing 32-bit values are generally thread-safe when multi-threading, however in a multi-processor scenario, are these reads/writes still thread-safe?
    Wednesday, January 5, 2011 11:38 PM

Answers

  • Read/Writes are atomic with regard to the register size. So on x32 machines you can read/write 32 bit values atomically. On x64 machines 64 bit values...

    Cache coherency is guaranteed via the MESI protocol. You do not have to worry about atomicity and cache flushing expect if you experience slow performance due to e.g. false sharing .

     

    But be ware things like

    i++;

    are NOT atomic since it does consist of

    1. Read Value from memory and store it in a register

    2. Increment register value

    3. Save register value back to memory.

    You need to read your code very careful to ensure that no such things like the above do happen.

    If you need to things like incrementing then you need to call the Interlocked.Increment/Decrement/CompareExchange methods. The Interlocked class is part of the System.Threading namespace.

    Yours,

       Alois Kraus

     

    • Marked as answer by eryang Tuesday, January 11, 2011 1:31 AM
    Thursday, January 6, 2011 12:53 AM

All replies

  • Read/Writes are atomic with regard to the register size. So on x32 machines you can read/write 32 bit values atomically. On x64 machines 64 bit values...

    Cache coherency is guaranteed via the MESI protocol. You do not have to worry about atomicity and cache flushing expect if you experience slow performance due to e.g. false sharing .

     

    But be ware things like

    i++;

    are NOT atomic since it does consist of

    1. Read Value from memory and store it in a register

    2. Increment register value

    3. Save register value back to memory.

    You need to read your code very careful to ensure that no such things like the above do happen.

    If you need to things like incrementing then you need to call the Interlocked.Increment/Decrement/CompareExchange methods. The Interlocked class is part of the System.Threading namespace.

    Yours,

       Alois Kraus

     

    • Marked as answer by eryang Tuesday, January 11, 2011 1:31 AM
    Thursday, January 6, 2011 12:53 AM
  •  

    We temporarily mark a reply since the thread idle for a long time, please remember to click "Mark as Answer" on the post that helps you, and to click "Unmark as Answer" if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.


    Eric Yang [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Tuesday, January 11, 2011 1:31 AM