동기화 개요

독점 잠금

lock 문

class ThreadUnsafe
{
  static int _val1 = 1, _val2 = 1;

  static void Go()
  {
    if (_val2 != 0)  Console.WriteLine(_val1 / _val2);
    _val2 = 0;
  }
}
class ThreadSafe
{
  static readonly object _locker = new object();
  static int _val1 = 1, _val2 = 1;

  static void Go()
  {
    lock(_locker)
    {
      if (_val2 != 0)  Console.WriteLine(_val1 / _val2);
      _val2 = 0;
    }
  }
}

Monitor.Enter와 Monitor.Exit

Monitor.Enter(_locker);
try
{
  if (_val2 != 0)  Console.WriteLine(_val1 / _val2);
  _val2 = 0;
}
finally { Monitor.Exit(_locker); }

lockTaken 메서드 중복 적재

public static void Enter(object obj, ref bool lockTaken);