欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#多线程学习之(三)生产者和消费者用法分析

程序员文章站 2023-11-21 16:37:28
本文实例讲述了c#多线程学习之生产者和消费者用法。分享给大家供大家参考。具体实分析如下: 前面的文章说过,每个线程都有自己的资源,但是代码区是共享的,即每个线程都可以执行...

本文实例讲述了c#多线程学习之生产者和消费者用法。分享给大家供大家参考。具体实分析如下:

前面的文章说过,每个线程都有自己的资源,但是代码区是共享的,即每个线程都可以执行相同的函数。这可能带来的问题就是几个线程同时执行一个函数,导致数据的混乱,产生不可预料的结果,因此我们必须避免这种情况的发生。

c#提供了一个关键字lock,它可以把一段代码定义为互斥段(critical section),互斥段在一个时刻内只允许一个线程进入执行,而其他线程必须等待。在c#中,关键字lock定义如下:

lock(expression) statement_block 

expression代表你希望跟踪的对象,通常是对象引用。
如果你想保护一个类的实例,一般地,你可以使用this;
如果你想保护一个静态变量(如互斥代码段在一个静态方法内部),一般使用类名就可以了。

而statement_block就是互斥段的代码,这段代码在一个时刻内只可能被一个线程执行。

下面是一个使用lock关键字的典型例子,在注释里说明了lock关键字的用法和用途。
示例如下:

using system;
using system.threading;
namespace threadsimple
{
 internal class account 
 {
  int balance;
  random r = new random();
  internal account(int initial) 
  {
   balance = initial;
  } 
  internal int withdraw(int amount) 
  {
   if (balance < 0)
   {
    //如果balance小于0则抛出异常
    throw new exception("negative balance");
   }
   //下面的代码保证在当前线程修改balance的值完成之前
   //不会有其他线程也执行这段代码来修改balance的值
   //因此,balance的值是不可能小于0 的
   lock (this)
   {
    console.writeline("current thread:"+thread.currentthread.name);
    //如果没有lock关键字的保护,那么可能在执行完if的条件判断之后
    //另外一个线程却执行了balance=balance-amount修改了balance的值
    //而这个修改对这个线程是不可见的,所以可能导致这时if的条件已经不成立了
    //但是,这个线程却继续执行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();
  }
 }
}

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写入数据。

示例如下:

public class cell
{
  int cellcontents; // cell对象里边的内容
  bool readerflag = false; // 状态标志,为true时可以读取,为false则正在写入
  public int readfromcell( )
  {
   lock(this) // lock关键字保证了什么,请大家看前面对lock的介绍
   {
    if (!readerflag)//如果现在不可读取
    { 
     try
     {
      //等待writetocell方法中调用monitor.pulse()方法
      monitor.wait(this);
     }
     catch (synchronizationlockexception e)
     {
      console.writeline(e);
     }
     catch (threadinterruptedexception e)
     {
      console.writeline(e);
     }
    }
    console.writeline("consume: {0}",cellcontents);
    readerflag = false;
    //重置readerflag标志,表示消费行为已经完成
    monitor.pulse(this); 
    //通知writetocell()方法(该方法在另外一个线程中执行,等待中)
   }
   return cellcontents;
  }
  public void writetocell(int n)
  {
   lock(this)
   {
    if (readerflag)
    {
     try
     {
      monitor.wait(this);
     }
     catch (synchronizationlockexception e)
     {
      //当同步方法(指monitor类除enter之外的方法)在非同步的代码区被调用
      console.writeline(e);
     }
     catch (threadinterruptedexception e)
     {
       //当线程在等待状态的时候中止 
      console.writeline(e);
     }
    }
    cellcontents = n;
    console.writeline("produce: {0}",cellcontents);
    readerflag = true; 
    monitor.pulse(this); 
    //通知另外一个线程中正在等待的readfromcell()方法
   }
  }
}

下面定义生产者类 cellprod 和消费者类 cellcons ,它们都只有一个方法threadrun(),以便在main()函数中提供给线程的threadstart代理对象,作为线程的入口。

public class cellprod
{
 cell cell; // 被操作的cell对象
 int quantity = 1; // 生产者生产次数,初始化为1 
 public cellprod(cell box, int request)
 {
  //构造函数
  cell = box; 
  quantity = request; 
 }
 public void threadrun( )
 {
  for(int looper=1; looper<=quantity; looper++)
  cell.writetocell(looper); //生产者向操作对象写入信息
 }
}
public class cellcons
{
 cell cell; 
 int quantity = 1; 

 public cellcons(cell box, int request)
 {
  //构造函数
  cell = box; 
  quantity = request; 
 }
 public void threadrun( )
 {
  int valreturned;
  for(int looper=1; looper<=quantity; looper++)
  valreturned=cell.readfromcell( );//消费者从操作对象中读取信息
 }
}

然后在下面这个类monitorsample的main()函数中,我们要做的就是创建两个线程分别作为生产者和消费者,使用cellprod.threadrun()方法和cellcons.threadrun()方法对同一个cell对象进行操作。

public class monitorsample
{
 public static void main(string[] args)
 {
  int result = 0; 
 //一个标志位,如果是0表示程序没有出错,如果是1表明有错误发生
  cell cell = new cell( ); 
  //下面使用cell初始化cellprod和cellcons两个类,生产和消费次数均为20次
  cellprod prod = new cellprod(cell, 20); 
  cellcons cons = new cellcons(cell, 20); 

  thread producer = new thread(new threadstart(prod.threadrun));
  thread consumer = new thread(new threadstart(cons.threadrun));
  //生产者线程和消费者线程都已经被创建,但是没有开始执行 
  try
  {
 producer.start( );
 consumer.start( ); 

 producer.join( ); 
 consumer.join( );
 console.readline();
  }
  catch (threadstateexception e)
  {
 //当线程因为所处状态的原因而不能执行被请求的操作
 console.writeline(e); 
 result = 1; 
  }
  catch (threadinterruptedexception e)
  {
 //当线程在等待状态的时候中止
 console.writeline(e); 
 result = 1; 
  }
  //尽管main()函数没有返回值,但下面这条语句可以向父进程返回执行结果
  environment.exitcode = result;
 }
}

在上面的例程中,同步是通过等待monitor.pulse()来完成的。首先生产者生产了一个值,而 同一时刻消费者处于等待状态,直到收到生产者的“脉冲(pulse)”通知它生产已经完成,此后消费者进入消费状态,而生产者开始等待消费者完成操作后将 调用monitor.pulese()发出的“脉冲”。

它的执行结果很简单:

produce: 1
consume: 1
produce: 2
consume: 2
produce: 3
consume: 3
...
...
produce: 20
consume: 20
 
事实上,这个简单的例子已经帮助我们解决了多线程应用程序中可能出现的大问题,只要领悟了解决线程间冲突的基本方法,很容易把它应用到比较复杂的程序中去。

希望本文所述对大家的c#程序设计有所帮助。