Will atomic operations block other threads?

前端 未结 5 433
难免孤独
难免孤独 2021-02-01 10:53

I am trying to make \"atomic vs non atomic\" concept settled in my mind. My first problem is I could not find \"real-life analogy\" on that. Like customer/restaurant relationshi

5条回答
  •  萌比男神i
    2021-02-01 11:23

    Atomic operation means the system performs an operation in its entirety or not at all. Reading or writing an int64 is atomic (64bits System & 64bits CLR) because the system read/write the 8 bytes in one single operation, readers do not see half of the new value being stored and half of the old value. But be carefull :

    long n = 0; // writing 'n' is atomic, 64bits OS & 64bits CLR
    long m = n; // reading 'n' is atomic
    ....// some code
    long o = n++; // is not atomic : n = n + 1 is doing a read then a write in 2 separate operations
    

    To make atomicity happens to the n++ you can use the Interlocked API :

    long o = Interlocked.Increment(ref n); // other threads are blocked while the atomic operation is running
    

提交回复
热议问题