F
Fernando Rodríguez
Hi,
I've been reading the multithreading tutorial at
http://www.yoda.arachsys.com/csharp/threads/locking.shtml (thanks Jon
and
there's one thing I don't understand.
Why do have to pass a parameter to lock, Monitor.Enter() and Monitor.Exit()?
Why is it necessary to create a new readonly variable for this purpose? (see
below, counterLock)
-----------------------------------------------------------------------------------------
Thread thread = new Thread( new ThreadStart( ThreadJob ) );
thread.Start();
for( int i=0; i < 5; ++i )
{
lock (counterLock)
{
int tmp = count;
Console.WriteLine("Read count={0}", tmp);
Thread.Sleep(50);
tmp++;
Console.WriteLine("Incremented tmp to {0}", tmp);
Thread.Sleep(20);
count = tmp;
Console.WriteLine("Written count={0}", tmp);
}
Thread.Sleep(30);
}
I've been reading the multithreading tutorial at
http://www.yoda.arachsys.com/csharp/threads/locking.shtml (thanks Jon

there's one thing I don't understand.
Why do have to pass a parameter to lock, Monitor.Enter() and Monitor.Exit()?
Why is it necessary to create a new readonly variable for this purpose? (see
below, counterLock)
-----------------------------------------------------------------------------------------
Thread thread = new Thread( new ThreadStart( ThreadJob ) );
thread.Start();
for( int i=0; i < 5; ++i )
{
lock (counterLock)
{
int tmp = count;
Console.WriteLine("Read count={0}", tmp);
Thread.Sleep(50);
tmp++;
Console.WriteLine("Incremented tmp to {0}", tmp);
Thread.Sleep(20);
count = tmp;
Console.WriteLine("Written count={0}", tmp);
}
Thread.Sleep(30);
}