线程的同步和通讯——生产者和消费者 假设这样一种情况,两个线程同时维护一个队列,如果一个线程对队列中添加元素,而另外一个线程从队列中取用元素,那么我们称添加元素的线程为生产者,称取用元素的线程为消费者。生产者与消费者问题看起来很简单,但是却是多线程应用中一个必须解决的问题,它涉及到线程之间的同步和通讯问题。 前面说过,每个线程都有自己的资源,但是代码区是共享的,即每个线程都可以执行相同的函数。但是多线程环境下,可能带来的问题就是几个线程同时执行一个函数,导致数据的混乱,产生不可预料的结果,因此我们必须避免这种情况的发生。C#提供了一个关键字lock,它可以把一段代码定义为互斥段(critical section),互斥段在一个时刻内只允许一个线程进入执行,而其他线程必须等待。在C#中,关键字lock定义如下:lock(expression) statement_block 
 expression代表你希望跟踪的对象,通常是对象引用。一般地,如果你想保护一个类的实例,你可以使用this;如果你希望保护一个静态变量(如互斥代码段在一个静态方法内部),一般使用类名就可以了。而statement_block就是互斥段的代码,这段代码在一个时刻内只可能被一个线程执行。   下面是一个使用lock关键字的典型例子,我将在注释里向大家说明lock关键字的用法和用途://lock.cs
using System;
using System.Threading; internal class Account 
{
  int balance;
  Random r = new Random();
  internal Account(int initial) 
  {
  balance = initial;
  }   internal int Withdraw(int amount) 
  {
  if (balance < 0) 
  {
    file://如果balance小于0则抛出异常
    throw new Exception("Negative Balance");
  }
  //下面的代码保证在当前线程修改balance的值完成之前
  //不会有其他线程也执行这段代码来修改balance的值
  //因此,balance的值是不可能小于0的
  lock (this)
  {
    Console.WriteLine("Current Thread:"+Thread.CurrentThread.Name);
    file://如果没有lock关键字的保护,那么可能在执行完if的条件判断之后
    file://另外一个线程却执行了balance=balance-amount修改了balance的值
    file://而这个修改对这个线程是不可见的,所以可能导致这时if的条件已经不成立了
    file://但是,这个线程却继续执行balance=balance-amount,所以导致balance可能小于0
    if (balance >= amount) 
    {
    Thread.Sleep(5);
    balance = balance - amount;
    return amount;
    } 
    else 
    {
    return 0; // transaction rejected
    }
  }
  }
  internal void DoTransactions() 
  {
  for (int i = 0; i < 100; i++) 
    Withdraw(r.Next(-50, 100));
  }
} internal class Test 
{
  static internal Thread[] threads = new Thread[10];
  public static void Main() 
  {
  Account acc = new Account (0);
  for (int i = 0; i < 10; i++) 
  {
    Thread t = new Thread(new ThreadStart(acc.DoTransactions));
    threads[i] = t;
  }
  for (int i = 0; i < 10; i++) 
    threads[i].Name=i.ToString();
  for (int i = 0; i < 10; i++) 
    threads[i].Start();
  Console.ReadLine();
  }
} 
 而多线程公用一个对象时,也会出现和公用代码类似的问题,这种问题就不应该使用lock关键字了,这里需要用到System.Threading中的一个类Monitor,我们可以称之为监视器,Monitor提供了使线程共享资源的方案。   Monitor类可以锁定一个对象,一个线程只有得到这把锁才可以对该对象进行操作。对象锁机制保证了在可能引起混乱的情况下一个时刻只有一个线程可以访问这个对象。Monitor必须和一个具体的对象相关联,但是由于它是一个静态的类,所以不能使用它来定义对象,而且它的所有方法都是静态的,不能使用对象来引用。下面代码说明了使用Monitor锁定一个对象的情形:......
Queue oQueue=new Queue();
......
Monitor.Enter(oQueue);
......//现在oQueue对象只能被当前线程操纵了
Monitor.Exit(oQueue);//释放锁 
 
如上所示,当一个线程调用Monitor.Enter()方法锁定一个对象时,这个对象就归它所有了,其它线程想要访问这个对象,只有等待它使用Monitor.Exit()方法释放锁。为了保证线程最终都能释放锁,你可以把Monitor.Exit()方法写在try-catch-finally结构中的finally代码块里。对于任何一个被Monitor锁定的对象,内存中都保存着与它相关的一些信息,其一是现在持有锁的线程的引用,其二是一个预备队列,队列中保存了已经准备好获取锁的线程,其三是一个等待队列,队列中保存着当前正在等待这个对象状态改变的队列的引用。当拥有对象锁的线程准备释放锁时,它使用Monitor.Pulse()方法通知等待队列中的第一个线程,于是该线程被转移到预备队列中,当对象锁被释放时,在预备队列中的线程可以立即获得对象锁。 

解决方案 »

  1.   

    初看起来,没有发现明显的问题,你能将:
    现在有个问题,在producerThread,consumerThread收到停止线程信号后,safeSetText执行到22222222,程序死锁在this.textBox1.Invoke(call, text);这个地方,而consumerThread还没有读完产生的列表。描述的,停止线程信号那块的处理代码也贴上来看看吗?
      

  2.   

    使用多线程更新UI时,最好使用委托Delegates
      

  3.   

    贴个完整的代码:
    delegate void _SafeSetTextCall(string text);    class Consumer
        {
            private Queue<int> _queue;
            private SyncEvents _syncEvents;
            private _SafeSetTextCall _call;        public Consumer(Queue<int> q, SyncEvents e, _SafeSetTextCall call)
            {
                _queue = q;
                _syncEvents = e;
                _call = call;
            }        public void ThreadRun()
            {
                int count = 0;
                while (WaitHandle.WaitAny(_syncEvents.EventArray) != 1 || _queue.Count() > 0)
                {
                    int item = 0;
                    lock (((ICollection)_queue).SyncRoot)
                    {
                        item = _queue.Dequeue();
                        Console.WriteLine("Consumer " + (count + 1).ToString() + ":" + item.ToString());
                    }
                    string desc = "Consumer " + (count + 1).ToString() + ":" + item.ToString();
                    lock (desc)
                    {
                        _call(desc);
                    }
                    for (int i = 0; i < 10000; i++)
                    {
                        Random rand = new Random();
                        int it = rand.Next();
                        Application.DoEvents();
                    }
                    count++;
                }
                Console.WriteLine("Consumer Thread: consumed {0} items", count);
            }
        }
    public partial class Form1 : Form
        {
            private SyncEvents _syncEvents;
            private Thread _producerThread;
            private Thread _consumerThread;
            public Form1()
            {
                InitializeComponent();
            }        private void button1_Click(object sender, EventArgs e)
            {
                Queue<int> queue = new Queue<int>();
                _syncEvents = new SyncEvents();            Console.WriteLine("Configuring worker threads...");
                Producer producer = new Producer(queue, _syncEvents);
                Consumer consumer = new Consumer(queue, _syncEvents, new _SafeSetTextCall(this.safeSetText));
                _producerThread = new Thread(producer.ThreadRun);
                _consumerThread = new Thread(consumer.ThreadRun);
                
                Console.WriteLine("Launching producer and consumer threads...");            _producerThread.Start();
                _consumerThread.Start();
                Console.WriteLine("Start Thread...");                        
            }        private void safeSetText(string text)
            {
                if (this.textBox1.InvokeRequired)
                {
                    _SafeSetTextCall call = delegate(string s)
                    {
                        Console.WriteLine("00000000000000000");
                        this.textBox1.Text = s;
                        Console.WriteLine("11111111111111111");
                    };                Console.WriteLine("222222222222");
                    lock (text)
                    {
                        this.textBox1.Invoke(call, text);
                    }
                    
                    Console.WriteLine("333333333333");
                }
                else
                {
                    Console.WriteLine("4444444444444");
                    this.textBox1.Text = text;
                }
            }        private void button2_Click(object sender, EventArgs e)
            {
                Console.WriteLine("Signaling threads to terminate...");
                _syncEvents.ExitThreadEvent.Set();            _producerThread.Join();
                _consumerThread.Join();
            }class SyncEvents
        {
            public SyncEvents()
            {
                _newItemEvent = new AutoResetEvent(false);
                _exitThreadEvent = new ManualResetEvent(false);
                _eventArray = new WaitHandle[2];
                _eventArray[0] = _newItemEvent;
                _eventArray[1] = _exitThreadEvent;
            }        public EventWaitHandle ExitThreadEvent
            {
                get { return _exitThreadEvent; }
            }        public EventWaitHandle NewItemEvent
            {
                get { return _newItemEvent; }
            }        public WaitHandle[] EventArray
            {
                get { return _eventArray; }
            }        private EventWaitHandle _newItemEvent;
            private EventWaitHandle _exitThreadEvent;
            private WaitHandle[] _eventArray;
        }