Value types immune from thread racing because of this? #83938
-
I heard value types like I understand if you modify a integer concurrently in two different thread it's not going to get corrupt bits instead each thread reads the original value then add a number then store the new value, now I am wondering if these operations are always going to be sequential meaning the thread that's adding something to the original value is always going to add it instead of reading the original value then having another one thread store whatever computed then it overwrites the computed result Rumor : https://stackoverflow.com/questions/11745440/what-operations-are-atomic-in-c |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 7 replies
-
https://github.com/dotnet/runtime/blob/main/docs/design/specs/Memory-model.md - I believe you should read this. It should clear most questions regarding memory operations in .Net runtime |
Beta Was this translation helpful? Give feedback.
-
If two operations are atomic themselves (for assignment, not the whole read-compute-write operation), and their result can't co-exist (a memory address can't have two values on processor with strong consistency model), they must happen in some order. |
Beta Was this translation helpful? Give feedback.
-
That is not guaranteed. In other words, this is not atomic: But thread-safety is a complicated topic. If you're not certain, the safer bet is to use locking instead of interlocked operations. |
Beta Was this translation helpful? Give feedback.
-
There's two different definitions of "atomic" being referenced here. The first, and better-known definition, is "operation" atomicity, which is what @svick is referring to (and everybody else seems to be as well). This requires locks or The second, not as commonly known, is "storage" atomicity, which depends heavily on processor, most usually on bit-width. This is where, if you had multiple threads trying to store a value, you could get some bits from one thread and some bits from another, "tearing" the value. Historically, this primarily came when trying to work with |
Beta Was this translation helpful? Give feedback.
There's two different definitions of "atomic" being referenced here.
The first, and better-known definition, is "operation" atomicity, which is what @svick is referring to (and everybody else seems to be as well). This requires locks or
Interlocked
. The catch is that you need multiple operations to be atomic, and addition is one operation... and read and store are two additional operations. This is mostly constant across all versions and platforms.The second, not as commonly known, is "storage" atomicity, which depends heavily on processor, most usually on bit-width. This is where, if you had multiple threads trying to store a value, you could get some bits from one thread and some bits …