C#多线程学习(三) 生产者和消费者
前面说过,每个线程都有自己的资源,但是代码区是共享的,即每个线程都可以执行相同的函数。这可能带来的问题就是几个线程同时执行一个函数,导致数据的混乱,产生不可预料的结果,因此我们必须避免这种情况的发生。
C#提供了一个关键字lock,它可以把一段代码定义为互斥段(critical section),互斥段在一个时刻内只允许一个线程进入执行,而其他线程必须等待。在C#中,关键字lock定义如下:
lock(expression) statement_block
expression代表你希望跟踪的对象,通常是对象引用。
如果你想保护一个类的实例,一般地,你可以使用this;
如果你想保护一个静态变量(如互斥代码段在一个静态方法内部),一般使用类名就可以了。
而statement_block就是互斥段的代码,这段代码在一个时刻内只可能被一个线程执行。
下面是一个使用lock关键字的典型例子,在注释里说明了lock关键字的用法和用途。
示例如下:
1 using System; 2 using System.Threading; 3 4 namespace ThreadSimple 5 { 6 internal class Account 7 { 8 int balance; 9 Random r = new Random(); 10 11 internal Account(int initial) 12 { 13 balance = initial; 14 } 15 16 internal int Withdraw(int amount) 17 { 18 if (balance < 0) 19 { 20 //如果balance小于0则抛出异常 21 throw new Exception("Negative Balance"); 22 } 23 //下面的代码保证在当前线程修改balance的值完成之前 24 //不会有其他线程也执行这段代码来修改balance的值 25 //因此,balance的值是不可能小于0 的 26 lock (this) 27 { 28 Console.WriteLine("Current Thread:"+Thread.CurrentThread.Name); 29 //如果没有lock关键字的保护,那么可能在执行完if的条件判断之后 30 //另外一个线程却执行了balance=balance-amount修改了balance的值 31 //而这个修改对这个线程是不可见的,所以可能导致这时if的条件已经不成立了 32 //但是,这个线程却继续执行balance=balance-amount,所以导致balance可能小于0 33 if (balance >= amount) 34 { 35 Thread.Sleep(5); 36 balance = balance - amount; 37 return amount; 38 } 39 else 40 { 41 return 0; // transaction rejected 42 } 43 } 44 } 45 internal void DoTransactions() 46 { 47 for (int i = 0; i < 100; i++) 48 Withdraw(r.Next(-50, 100)); 49 } 50 } 51 52 internal class Test 53 { 54 static internal Thread[] threads = new Thread[10]; 55 public static void Main() 56 { 57 Account acc = new Account (0); 58 for (int i = 0; i < 10; i++) 59 { 60 Thread t = new Thread(new ThreadStart(acc.DoTransactions)); 61 threads[i] = t; 62 } 63 for (int i = 0; i < 10; i++) 64 threads[i].Name=i.ToString(); 65 for (int i = 0; i < 10; i++) 66 threads[i].Start(); 67 Console.ReadLine(); 68 } 69 } 70 }
Monitor 类锁定一个对象
当多线程公用一个对象时,也会出现和公用代码类似的问题,这种问题就不应该使用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()方法通知等待队列中的第一个线程,于是该线程被转移到预备队列中,当对象锁被释放时,在预备队列中的线程可以立即获得对象锁。
下面是一个展示如何使用lock关键字和Monitor类来实现线程的同步和通讯的例子,也是一个典型的生产者与消费者问题。
这个例程中,生产者线程和消费者线程是交替进行的,生产者写入一个数,消费者立即读取并且显示(注释中介绍了该程序的精要所在)。
用到的系统命名空间如下:
using System;
using System.Threading;
首先,定义一个被操作的对象的类Cell,在这个类里,有两个方法:ReadFromCell()和WriteToCell。消费者线程将调用ReadFromCell()读取cellContents的内容并且显示出来,生产者进程将调用WriteToCell()方法向cellContents写入数据。
示例如下:
1 public class Cell 2 { 3 int cellContents; // Cell对象里边的内容 4 bool readerFlag = false; // 状态标志,为true时可以读取,为false则正在写入 5 public int ReadFromCell( ) 6 { 7 lock(this) // Lock关键字保证了什么,请大家看前面对lock的介绍 8 { 9 if (!readerFlag)//如果现在不可读取 10 { 11 try 12 { 13 //等待WriteToCell方法中调用Monitor.Pulse()方法 14 Monitor.Wait(this); 15 } 16 catch (SynchronizationLockException e) 17 { 18 Console.WriteLine(e); 19 } 20 catch (ThreadInterruptedException e) 21 { 22 Console.WriteLine(e); 23 } 24 } 25 Console.WriteLine("Consume: {0}",cellContents); 26 readerFlag = false; 27 //重置readerFlag标志,表示消费行为已经完成 28 Monitor.Pulse(this); 29 //通知WriteToCell()方法(该方法在另外一个线程中执行,等待中) 30 } 31 return cellContents; 32 } 33 34 public void WriteToCell(int n) 35 { 36 lock(this) 37 { 38 if (readerFlag) 39 { 40 try 41 { 42 Monitor.Wait(this); 43 } 44 catch (SynchronizationLockException e) 45 { 46 //当同步方法(指Monitor类除Enter之外的方法)在非同步的代码区被调用 47 Console.WriteLine(e); 48 } 49 catch (ThreadInterruptedException e) 50 { 51 //当线程在等待状态的时候中止 52 Console.WriteLine(e); 53 } 54 } 55 cellContents = n; 56 Console.WriteLine("Produce: {0}",cellContents); 57 readerFlag = true; 58 Monitor.Pulse(this); 59 //通知另外一个线程中正在等待的ReadFromCell()方法 60 } 61 } 62 }
下面定义生产者类 CellProd 和消费者类 CellCons ,它们都只有一个方法ThreadRun(),以便在Main()函数中提供给线程的ThreadStart代理对象,作为线程的入口。
1 public class CellProd 2 { 3 Cell cell; // 被操作的Cell对象 4 int quantity = 1; // 生产者生产次数,初始化为1 5 6 public CellProd(Cell box, int request) 7 { 8 //构造函数 9 cell = box; 10 quantity = request; 11 } 12 public void ThreadRun( ) 13 { 14 for(int looper=1; looper<=quantity; looper++) 15 cell.WriteToCell(looper); //生产者向操作对象写入信息 16 } 17 } 18 19 public class CellCons 20 { 21 Cell cell; 22 int quantity = 1; 23 24 public CellCons(Cell box, int request) 25 { 26 //构造函数 27 cell = box; 28 quantity = request; 29 } 30 public void ThreadRun( ) 31 { 32 int valReturned; 33 for(int looper=1; looper<=quantity; looper++) 34 valReturned=cell.ReadFromCell( );//消费者从操作对象中读取信息 35 } 36 }
然后在下面这个类MonitorSample的Main()函数中,我们要做的就是创建两个线程分别作为生产者和消费者,使用CellProd.ThreadRun()方法和CellCons.ThreadRun()方法对同一个Cell对象进行操作。
1 public class MonitorSample 2 { 3 public static void Main(String[] args) 4 { 5 int result = 0; //一个标志位,如果是0表示程序没有出错,如果是1表明有错误发生 6 Cell cell = new Cell( ); 7 8 //下面使用cell初始化CellProd和CellCons两个类,生产和消费次数均为20次 9 CellProd prod = new CellProd(cell, 20); 10 CellCons cons = new CellCons(cell, 20); 11 12 Thread producer = new Thread(new ThreadStart(prod.ThreadRun)); 13 Thread consumer = new Thread(new ThreadStart(cons.ThreadRun)); 14 //生产者线程和消费者线程都已经被创建,但是没有开始执行 15 try 16 { 17 producer.Start( ); 18 consumer.Start( ); 19 20 producer.Join( ); 21 consumer.Join( ); 22 Console.ReadLine(); 23 } 24 catch (ThreadStateException e) 25 { 26 //当线程因为所处状态的原因而不能执行被请求的操作 27 Console.WriteLine(e); 28 result = 1; 29 } 30 catch (ThreadInterruptedException e) 31 { 32 //当线程在等待状态的时候中止 33 Console.WriteLine(e); 34 result = 1; 35 } 36 //尽管Main()函数没有返回值,但下面这条语句可以向父进程返回执行结果 37 Environment.ExitCode = result; 38 } 39 }
在上面的例程中,同步是通过等待Monitor.Pulse()来完成的。首先生产者生产了一个值,而同一时刻消费者处于等待状态,直到收到生产者的“脉冲(Pulse)”通知它生产已经完成,此后消费者进入消费状态,而生产者开始等待消费者完成操作后将调用Monitor.Pulese()发出的“脉冲”。
它的执行结果很简单:
Produce: 1
Consume: 1
Produce: 2
Consume: 2
Produce: 3
Consume: 3
...
...
Produce: 20
Consume: 20
事实上,这个简单的例子已经帮助我们解决了多线程应用程序中可能出现的大问题,只要领悟了解决线程间冲突的基本方法,很容易把它应用到比较复杂的程序中去。

浙公网安备 33010602011771号