Trying to make sure I understand locking correctly


so far i've used locking in simple way, i'm trying optimize code performance , need make sure of things.


supposedly have example locking code defined here:
http://msdn.microsoft.com/en-us/library/c5kehkcz%28v=vs.71%29.aspx
(account balance cannot go negative).

but, following alterations: (questions below)

class balanceentry  {      public int value;  }    class account  {      dictionary<int, balanceentry> b = new dictionary<int, balanceentry>();          public account( int initial )      {          b.add( 0, new balanceentry() );          b[0].value = initial;      }      	int withdraw1( int amount )   	{   		lock ( )   		{   			// code ...   		}   	}  	  	int withdraw2( int amount )   	{   		lock ( b )   		{   			// code ...   		}   	}	  	  	int withdraw3( int amount )   	{   		lock ( b[0] )   		{   			// code ...   		}   	}		    }


if there 3 different threads called withdraw1, withdraw2 , withdraw3 @ same time, lock wouldn't work, correct? because it's different object gets locked?

furthermore, code:

	int withdraw( int amount )   	{   		balance tolock = b[0];  		lock ( tolock )   		{   			// code ...   		}   	}  	  	int withdraw( int amount )   	{   		lock ( b[0] )   		{   			// code ...   		}   	}
lock work, right? because although locking different variable, it's still same object.

just making sure avoid catastrophy when system starts getting high loads.

you're assumptions correct - except last.

locking b[0] not safe, change balance entry  cause b[0] different object.

also, dictionary isn't thread safe,  adding or changing values need lock on object shared between threads.

this partly why it's common suggest locking on private object created solely purpose of lock - doing simplifies code , helps prevent bugs.  adding member class (like "private readonly object synchronizationobject = new object();") , locking on safe practice, , can prevent subtle bugs.

on side note: might want @ concurrentdictionary<t,u> if you're going using dictionary multiple threads.  this provides thread safe dictionary fine grained locking (but requires .net 4).


reed copsey, jr. - http://reedcopsey.com
if post answers question, please click "mark answer" on post , "mark helpful".



Visual Studio Languages  ,  .NET Framework  >  Visual C#



Comments

Popular posts from this blog

Azure DocumentDB Owner resource does not exist

job syspolicy_purge_history job fail in sqlserver 2008

Trying to register with public marketplace error with 'Get-AzureStackStampInformation'