本文介绍了多线程共享对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



想知道下图中的线程是否共享相同的队列和锁:

[代码]

Hi,

Wanted to know if my threads in the illustration below are sharing the same queue and lock:

[code]

class ThreadCls
{
   Queue q = new Queue();
   Threads[] t = new Threads[4];
   object sync = new Object();
   EventWaitHandle ewh = new AutoResetEvent(false);

   ThreadCls()
   {
      for(int i = 0; i < 4; i++)
      {
          t[i] = new Thread(doWork);
          t.Start();
      }
   }

   public void getData(object data)
   {
      lock(sync)
      {
          q.Enqueue(data);
      }
      ewh.Set();
   }
   public void doWork()
   {
      while(true)
      {
          lock(sync)
          {
              object o = q.Dequeue();
          }
              // processing logic...
              // etc...

         ewh.WaitOne();
      }
   }
}

推荐答案


这篇关于多线程共享对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 06:34
查看更多