Under C# is Int64 use on a 32 bit processor dangerous

前端 未结 6 1211
失恋的感觉
失恋的感觉 2020-12-31 03:41

I read in the MS documentation that assigning a 64-bit value on a 32-bit Intel computer is not an atomic operation; that is, the operation is not thread safe. This means tha

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-31 04:13

    Is this really true? Yes, as it turns out. If your registers only have 32 bits in them, and you need to store a 64-bit value to some memory location, it's going to take two load operations and two store operations. If your process gets interrupted by another process between these two load/stores, the other process might corrupt half your data! Strange but true. This has been a problem on every processor ever built - if your datatype is longer than your registers, you will have concurrency issues.

    Is this something I would worry about in the real world? Yes and no. Since almost all modern programming is given its own address space, you will only need to worry about this if you're doing multi-threaded programming.

    If my application is multi-threaded do I really need to surround all my Int64 assignments with locking code? Sadly, yes if you want to get technical. It's usually easier in practice to use a Mutex or Semaphore around larger code blocks than to lock every individual set statement on globally accessible variables.

提交回复
热议问题