Friday, July 29, 2011

Reentrant lock acquires in CLR.

I always like when a post gets to the point (especially after searching in Google). In short, if you perform an operation that waits to acquire a lock, the thread doesn't actually stop.

In concrete terms of .NET coding, if you call the WaitOne method on a thread, it may still process events that the CLR deems "high priority". This can be a big problem if the event handlers go into the critical region you are trying to protect.

int criticalRegion = 0;

private void criticalRegionWait() 
{
   AutoResetEvent are = new AutoResetEvent(false);
   Thread thread = new Thread(() => 
      { 
         criticalRegion = -1
         Debug.WriteLine(criticalRegion);
         are.Set();
      });
   thread.SetApartmentState(ApartmentState.STA);
   thread.IsBackground = true;
   thread.Start();
}

private void criticalRegionUpdateEvent(object sender, EventArgs e) 
{
   criticalRegion = 1;
}
In the above example, if there is a high priority event that has criticalRegionUpdateEvent in its call path a race condition is possible. While criticalRegionWait waits for the thread to finish, the criticalRegionUpdateEvent has a chance of setting criticalRegion = 1 so that WriteLine ends up printing 1 instead of -1.

No comments:

Post a Comment