欢迎光临
我们一直在努力

建站超值云服务器,限时71元/月

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

public class monitorsample
{
  public static void main(string[] args)
  {
  int result = 0; file://一个标志位,如果是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)
  {
    file://当线程因为所处状态的原因而不能执行被请求的操作
    console.writeline(e);
    result = 1;
  }
  catch (threadinterruptedexception e)
  {
    file://当线程在等待状态的时候中止
    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

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

  四、线程池和定时器——多线程的自动管理
在多线程的程序中,经常会出现两种情况。一种情况下,应用程序中的线程把大部分的时间花费在等待状态,等待某个事件发生,然后才能给予响应;而另外一种情况则是线程平常都处于休眠状态,只是周期性地被唤醒。在.net framework里边,我们使用threadpool来对付第一种情况,使用timer来对付第二种情况。

threadpool类提供一个由系统维护的线程池——可以看作一个线程的容器,该容器需要windows 2000以上版本的系统支持,因为其中某些方法调用了只有高版本的windows才有的api函数。你可以使用threadpool.queueuserworkitem()方法将线程安放在线程池里,该方法的原型如下:

//将一个线程放进线程池,该线程的start()方法将调用waitcallback代理对象代表的函数
public static bool queueuserworkitem(waitcallback);
//重载的方法如下,参数object将传递给waitcallback所代表的方法
public static bool queueuserworkitem(waitcallback, object);

要注意的是,threadpool类也是一个静态类,你不能也不必要生成它的对象,而且一旦使用该方法在线程池中添加了一个项目,那么该项目将是没有办法取消的。在这里你无需自己建立线程,只需把你要做的工作写成函数,然后作为参数传递给threadpool.queueuserworkitem()方法就行了,传递的方法就是依靠waitcallback代理对象,而线程的建立、管理、运行等等工作都是由系统自动完成的,你无须考虑那些复杂的细节问题,线程池的优点也就在这里体现出来了,就好像你是公司老板——只需要安排工作,而不必亲自动手。
下面的例程演示了threadpool的用法。首先程序创建了一个manualresetevent对象,该对象就像一个信号灯,可以利用它的信号来通知其它线程,本例中当线程池中所有线程工作都完成以后,manualresetevent的对象将被设置为有信号,从而通知主线程继续运行。它有几个重要的方法:reset(),set(),waitone()。初始化该对象时,用户可以指定其默认的状态(有信号/无信号),在初始化以后,该对象将保持原来的状态不变直到它的reset()或者set()方法被调用,reset()方法将其设置为无信号状态,set()方法将其设置为有信号状态。waitone()方法使当前线程挂起直到manualresetevent对象处于有信号状态,此时该线程将被激活。然后,程序将向线程池中添加工作项,这些以函数形式提供的工作项被系统用来初始化自动建立的线程。当所有的线程都运行完了以后,manualresetevent.set()方法被调用,因为调用了manualresetevent.waitone()方法而处在等待状态的主线程将接收到这个信号,于是它接着往下执行,完成后边的工作。

using system;
using system.collections;
using system.threading;

//这是用来保存信息的数据结构,将作为参数被传递
public class somestate
{
  public int cookie;
  public somestate(int icookie)
  {
  cookie = icookie;
  }
}

public class alpha
{
  public hashtable hashcount;
  public manualresetevent eventx;
  public static int icount = 0;
  public static int imaxcount = 0;
  public alpha(int maxcount)
  {
  hashcount = new hashtable(maxcount);
  imaxcount = maxcount;
  }

  file://线程池里的线程将调用beta()方法
  public void beta(object state)
  {
  //输出当前线程的hash编码值和cookie的值
  console.writeline(" {0} {1} :", thread.currentthread.gethashcode(),
  ((somestate)state).cookie);
  console.writeline("hashcount.count=={0}, thread.currentthread.gethashcode()=={1}", hashcount.count, thread.currentthread.gethashcode());
  lock (hashcount)
  {
    file://如果当前的hash表中没有当前线程的hash值,则添加之
    if (!hashcount.containskey(thread.currentthread.gethashcode()))
    hashcount.add (thread.currentthread.gethashcode(), 0);
    hashcount[thread.currentthread.gethashcode()] =
((int)hashcount[thread.currentthread.gethashcode()])+1;
  }

  int ix = 2000;
  thread.sleep(ix);
  //interlocked.increment()操作是一个原子操作,具体请看下面说明
  interlocked.increment(ref icount);
  if (icount == imaxcount)
  {
    console.writeline();
    console.writeline("setting eventx ");
    eventx.set();
  }
  }
}

public class simplepool
{
  public static int main(string[] args)
  {
  console.writeline("thread pool sample:");
  bool w2k = false;
  int maxcount = 10;//允许线程池中运行最多10个线程
  //新建manualresetevent对象并且初始化为无信号状态
  manualresetevent eventx = new manualresetevent(false);
  console.writeline("queuing {0} items to thread pool", maxcount);
  alpha oalpha = new alpha(maxcount); file://创建工作项
  //注意初始化oalpha对象的eventx属性
  oalpha.eventx = eventx;
  console.writeline("queue to thread pool 0");
  try
  {
    file://将工作项装入线程池
    file://这里要用到windows 2000以上版本才有的api,所以可能出现notsupportexception异常
    threadpool.queueuserworkitem(new waitcallback(oalpha.beta),
    new somestate(0));
    w2k = true;
  }
  catch (notsupportedexception)
  {
    console.writeline("these apis may fail when called on a non-windows 2000 system.");
    w2k = false;
  }
  if (w2k)//如果当前系统支持threadpool的方法.
  {
    for (int iitem=1;iitem < maxcount;iitem++)
    {
    //插入队列元素
    console.writeline("queue to thread pool {0}", iitem);
    threadpool.queueuserworkitem(new waitcallback(oalpha.beta),new somestate(iitem));
    }
    console.writeline("waiting for thread pool to drain");
    file://等待事件的完成,即线程调用manualresetevent.set()方法
    eventx.waitone(timeout.infinite,true);
    file://waitone()方法使调用它的线程等待直到eventx.set()方法被调用
    console.writeline("thread pool has been drained (event fired)");
    console.writeline();
    console.writeline("load across threads");
    foreach(object o in oalpha.hashcount.keys)
    console.writeline("{0} {1}", o, oalpha.hashcount[o]);
  }
  console.readline();
  return 0;

  }
}

程序中有些小地方应该引起我们的注意。somestate类是一个保存信息的数据结构,在上面的程序中,它作为参数被传递给每一个线程,你很容易就能理解这个,因为你需要把一些有用的信息封装起来提供给线程,而这种方式是非常有效的。程序出现的interlocked类也是专为多线程程序而存在的,它提供了一些有用的原子操作,所谓原子操作就是在多线程程序中,如果这个线程调用这个操作修改一个变量,那么其他线程就不能修改这个变量了,这跟lock关键字在本质上是一样的。

我们应该彻底地分析上面的程序,把握住线程池的本质,理解它存在的意义是什么,这样我们才能得心应手地使用它。下面是该程序的输出结果:

thread pool sample:
queuing 10 items to thread pool
queue to thread pool 0
queue to thread pool 1
…
…
queue to thread pool 9
waiting for thread pool to drain
98 0 :
hashcount.count==0, thread.currentthread.gethashcode()==98
100 1 :
hashcount.count==1, thread.currentthread.gethashcode()==100
98 2 :
…
…
setting eventx
thread pool has been drained (event fired)
load across threads
101 2
100 3
98 4
102 1

与threadpool类不同,timer类的作用是设置一个定时器,定时执行用户指定的函数,而这个函数的传递是靠另外一个代理对象timercallback,它必须在创建timer对象时就指定,并且不能更改。定时器启动后,系统将自动建立一个新的线程,并且在这个线程里执行用户指定的函数。下面的语句初始化了一个timer对象:

timer timer = new timer(timerdelegate, s,1000, 1000);

 第一个参数指定了timercallback代理对象;第二个参数的意义跟上面提到的waitcallback代理对象的一样,作为一个传递数据的对象传递给要调用的方法;第三个参数是延迟时间——计时开始的时刻距现在的时间,单位是毫秒;第四个参数是定时器的时间间隔——计时开始以后,每隔这么长的一段时间,timercallback所代表的方法将被调用一次,单位也是毫秒。这句话的意思就是将定时器的延迟时间和时间间隔都设为1秒钟。

定时器的设置是可以改变的,只要调用timer.change()方法,这是一个参数类型重载的方法,一般使用的原型如下:

 public bool change(long, long);

  下面这段代码将前边设置的定时器修改了一下:

 timer.change(10000,2000);

很显然,定时器timer的时间间隔被重新设置为2秒,停止计时10秒后生效。

下面这段程序演示了timer类的用法。

using system;
using system.threading;
class timerexamplestate
{
  public int counter = 0;
  public timer tmr;
}

class app
{
  public static void main()
  {
  timerexamplestate s = new timerexamplestate();

  //创建代理对象timercallback,该代理将被定时调用
  timercallback timerdelegate = new timercallback(checkstatus);

  //创建一个时间间隔为1s的定时器
  timer timer = new timer(timerdelegate, s,1000, 1000);
  s.tmr = timer;

  //主线程停下来等待timer对象的终止
  while(s.tmr != null)
    thread.sleep(0);
  console.writeline("timer example done.");
  console.readline();
  }
  file://下面是被定时调用的方法

  static void checkstatus(object state)
  {
  timerexamplestate s =(timerexamplestate)state;
  s.counter++;
  console.writeline("{0} checking status {1}.",datetime.now.timeofday, s.counter);
  if(s.counter == 5)
  {
    file://使用change方法改变了时间间隔
    (s.tmr).change(10000,2000);
    console.writeline("changed…");
  }
  if(s.counter == 10)
  {
    console.writeline("disposing of timer…");
    s.tmr.dispose();
    s.tmr = null;
  }
  }
}

程序首先创建了一个定时器,它将在创建1秒之后开始每隔1秒调用一次checkstatus()方法,当调用5次以后,在checkstatus()方法中修改了时间间隔为2秒,并且指定在10秒后重新开始。当计数达到10次,调用timer.dispose()方法删除了timer对象,主线程于是跳出循环,终止程序。程序执行的结果如下:

上面就是对threadpool和timer两个类的简单介绍,充分利用系统提供的功能,可以为我们省去很多时间和精力——特别是对很容易出错的多线程程序。同时我们也可以看到.net framework强大的内置对象,这些将对我们的编程带来莫大的方便。

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 »
分享到: 更多 (0)

相关推荐

  • 暂无文章