C#多线程同步lock、Mutex的实现

  class TestHelper

  {

  public TestHelper() { }

  List<People> m_data = new List<People>();

  int m_iComplete;

  private void LockThread(object obj)

  {

  List<object> parameters = (List<object>)obj;

  int idx = (int)parameters[0];

  while (true)

  {

  People data = null;

  lock(this)

  {

  if (m_iComplete >= m_data.Count)

  {

  return;

  }

  data = m_data[m_iComplete];

  Interlocked.Increment(ref m_iComplete);

  data.age = data.id;

  Console.Write("======");

  Console.WriteLine("id:" + data.id.ToString() + ",age:" + data.age.ToString());

  }

  }

  }

  //测试lock

  public void TestLock()

  {

  DateTime time1 = DateTime.Now;

  m_iComplete = 0;

  m_data.Clear();

  for (int i = 0; i < 10000;i++)

  {

  m_data.Add(new People(i + 1));

  }

  List<Thread> threads = new List<Thread>();

  for (int i = 0; i < Environment.ProcessorCount; i++)

  {

  Thread th = new Thread(LockThread);

  th.IsBackground = true;

  List<object> objs = new List<object>();

  objs.Add(i + 1);

  th.Start(objs);

  threads.Add(th);

  }

  foreach (var th in threads)

  {

  th.Join();

  }

  DateTime time2 = DateTime.Now;

  TimeSpan deltaTime = time2.Subtract(time1);

  Console.Write("===================耗时: ");

  Console.WriteLine(deltaTime.TotalSeconds);

  }

  Mutex m_mutex = new Mutex();

  private void MutexThread(object obj)

  {

  List<object> parameters = (List<object>)obj;

  int idx = (int)parameters[0];

  while (true)

  {

  People data = null;

  //开启

  m_mutex.WaitOne();

  if (m_iComplete >= m_data.Count)

  {

  //释放

  m_mutex.ReleaseMutex();

  return;

  }

  data = m_data[m_iComplete];

  Interlocked.Increment(ref m_iComplete);

  data.age = data.id;

  Console.Write("======");

  Console.WriteLine("id:" + data.id.ToString() + ",age:" + data.age.ToString());

  //释放

  m_mutex.ReleaseMutex();

  }

  }

  //测试mutex

  public void TestMutex()

  {

  DateTime time1 = DateTime.Now;

  m_iComplete = 0;

  m_data.Clear();

  for (int i = 0; i < 10000; i++)

  {

  m_data.Add(new People(i + 1));

  }

  List<Thread> threads = new List<Thread>();

  for (int i = 0;i<Environment.ProcessorCount;i++)

  {

  Thread th = new Thread(MutexThread);

  List<object> objs = new List<object>();

  objs.Add(i + 1);

  th.Start(objs);

  threads.Add(th);

  }

  foreach(var th in threads)

  {

  //同步等待

  th.Join();

  }

  DateTime time2 = DateTime.Now;

  TimeSpan deltaTime = time2.Subtract(time1);

  int sec = (int)deltaTime.TotalSeconds;

  Console.Write("===================耗时: ");

  Console.WriteLine(deltaTime.TotalSeconds);

  }

  }