Open the lock

Marcin Dudek

About me

Marcin Dudek




make-sense.it

Why threading?

What is synchronisation?

  • Critical section
  • Critical region

Synchronisation

Kernel objects

.NET abstractions

WaitHandle

Mutex

Mutual Exclusion

  • Named Mutex
  • Knows the owner

Semaphore

Multiple can access critical region

  • Named Semaphore
  • Knows the owner

AutoResetEvent

ManualResetEvent

  • Named version only through EventWaitHandle
  • What about owner?
  • OpenExisting

Slim versions

  • SemaphoreSlim
  • ManualResetEventSlim

lock

  • Easiest and most common way to protect shared state.
  • We need only reference type.

'Safe' example


public class Manager
{
    public void SuperSafeMethod()
    {
        object locker = new object();
        lock (locker)
        {
        }
    }
}
                

'Safe' example


public class Manager
{
    private double penetration;

    public void Increment()
    {
        lock((object)penetration)
        {
            penetration++;
        }
    }
}
                

lock - pre .NET 4.0


Monitor.Enter(locker);
try
{
    // access to shared state
}
finally
{
    Monitor.Exit(locker);
}
                

lock - post .NET 4.0


bool lockTaken;
try
{
    Monitor.Enter(locker, out lockTaken)
    // access to shared state
}
finally
{
    if(lockTaken)
    {
        Monitor.Exit(locker);
    }            
}
                

Monitor

  • Critical section (Enter, Exit)
  • Notification (Pulse, PulseAll)

lock

  • Knows the owner
  • Recursion count

Object in memory

How lock works

Thin lock

Sygnaling

Synchronized


public class Manager
{
    [MethodImplAttribute(MethodImplOptions.Synchronized)] 
    public void Increment(){ }
}
                

ReaderWriterLock

Why?

  • Performance
  • There is also slim version!

Sources

  • Concurrent Programming on Windws - Joe Duffy
  • Joe Duffy blog
  • Advanced .NET Debugging - Mario Hewardt

Q&A




make-sense.it
7.03.2017 (Tuesday)