What is non threadsafe about a simple get set property in C #?

I read a lot of discussions and examples of how to make a property thread safe. There is one on the page this threadafe wrapper class

The given example:

internal class MyThreadSafeCass { // *** Lock *** private object PropertyLock = new object(); // *** Property *** private int m_Property = 0; // *** Thread-safe access to Property using locking *** internal int Property { get { lock (PropertyLock) { return m_Property; } } set { lock (PropertyLock) { m_Property = value; } } } } 

It’s clear what is happening here and what the locks are doing, but I'm struggling to understand why this is necessary. Why are the following not thread safe? What could go wrong?

 internal class MyThreadSafeCass { // *** Property *** private int m_Property = 0; // *** Thread-safe access to Property using locking *** internal int Property { get { return m_Property; } set { m_Property = value; } } } 
+5
source share
2 answers

@ Enigmatism is gaining prestige here (if not the point, unfortunately), referring to this blog about missed locks , which, in turn, links the links to this blog about optimizing processor reordering , which is the real meat of the answer.

In general, CPUs can (and do) apply optimization to code, which includes changing the order in which read / write operations are performed. These changes ensure that they are consistent and invisible in the thread in which they are executed. However, they cannot (cannot) guarantee consistency between multiple threads accessing shared memory. A lock, as shown in the example in the initial question, imposes restrictions on access to this shared memory, which restore consistency.

As I said, this is a summary. I can’t add anything to the description on the blogs related to the above, so put off anyone interested in the full answer to follow these links.

@Enigmativity, I will still accept this as a response from you if you post it as such. Otherwise, I will accept this answer and close it.

0
source

expression of type: m_Property ++; in more than one thread, parallel returns different values. Especially on a multi-core processor.

  • The old value is loaded into the processor cache.
  • The value will increase by cpu
  • The new value will be stored in memory.

Example:

  • core will load the value as 10
  • core two will load the value as 10 at the same time as the core
  • both add one (value is 11)
  • both will store data in memory
  • the result will be 11.
  • but you expect 12

See details

0
source

All Articles