Blog Stats
  • Posts - 99
  • Articles - 5
  • Comments - 39
  • Trackbacks - 108

 

On my way back to New Orleans

Have not been back since X-Mas ...

I just have to say my verizon broadband card is the best investment I have made in a long time. Imagine being on a road trip writing in your blog and playing a game of online chess while orderring a new desktop from Dell... How cool. unfortunately I only have about an hour of battery :-/

 

A few people either made comments or sent emails on my last post regarding what I was saying about thread safety and the needless use of synchronization code I see alot of.

I am in particular referring to the fact that the CLR assures the astomicty of certain operations. One of these operations is the assignment of variables that are either the same size as it's native reference size or smaller (on most platforms 32 bits though this is moving to 64 quickly). Because of this the following code is thread safe.

public class Customer {
   private int m_Age;
   public int Age {
      get { return m_Age; }
      set { m_Age = value; }
   }
}

You will notice that I have no locking code in the Age getter and setter, this is on purpose. Since the data type (int) is the same size as the native reference the copying is assured to be atomic.

Many would write the code as

public class Customer {
   private int m_Age;
   private object m_SyncLock;
   public int Age {
      get { lock(m_SyncLock) { return m_Age; }}
      set { lock(m_SyncLock) {m_Age = value; }}
   }
}

The reason we would put locks around the getter and setter is because it is feasable that thread 1 is half way through setting the variable m_Age when it is context switched out and thread 2 then tries to access m_Age. This can not however happen within the CLR because atomicity is gaurenteed on the setting operation within thread 1. The locking has a high cost associated with it and should be removed whereever possible (needless to say the more things we can do without forcing synchronization the more efficient our threaded code will be).

This should also be looked at as a great reason why you should never use the synchronized attribute. Thge synchronized attribute will place locks around every bit of code, even the code that does not need it (like in the example). This “blanket” coverage of synchronization can bring your code to a crawl.

What I find particularly hilarious is that one of the top 3 reasons listed for using a property instead of public variable is “Thread Safety”, so you can lock around the variable. Just keep in mind that reference sized variables are assured to be done through an atomic operation. The use of properties should be the REAL reasons that you want to use properties ... indirection.

Just some quick thoughts ... On to beignets at the french market and beer.

 


Feedback

No comments posted yet.


Post a comment





 

Please add 2 and 3 and type the answer here:

 

 

Copyright © Greg Young