zoukankan      html  css  js  c++  java
  • Monitor同步的一个例子

    网上看到一篇介绍Monitor同步的文章,写的挺好的。文中给了一个生产者消费者的例子,拿过来修改了一下,主要改动在于添加了边界条件和主应用程序的退出等待。
    class MonitorWaitPulse
    {
    private int n = 1;
    private int max = 5;

    private object monitor = new object();

    public void Produce()
    {
    lock (monitor)
    {
    for (; n <= max; n++)
    {
    Console.WriteLine("Mom:the " + n.ToString() + " cake is ready");
    //tell the child that the cake is ready
    Monitor.Pulse(monitor);
    //if all cakes done,finish the job
    if (n == max)
    {
    Console.WriteLine("Mom:job done");
    break;
    }
    //wait the child to finishe the cake
    Monitor.Wait(monitor);
    }
    }
    }

    public void Consume()
    {
    lock (monitor)
    {
    while (n <= max)
    {
    Console.WriteLine("Child:eat the " + n.ToString() + " cake");
    //ask mom to make next cake
    Monitor.Pulse(monitor);
    if (n == max)
    {
    Console.WriteLine("Child: job done");
    break;
    }
    //wait mom to make the cake
    Monitor.Wait(monitor);
    }
    }
    }

    static void Main(string[] args)
    {
    MonitorWaitPulse obj = new MonitorWaitPulse();
    Thread tProduce = new Thread(new ThreadStart(obj.Produce));
    Thread tConsume = new Thread(new ThreadStart(obj.Consume));
    //Start threads.
    tProduce.Start();
    tConsume.Start();

    tProduce.Join();
    tConsume.Join();
    Console.ReadLine();
    }
    }

    很简单的例子,就不做多的解释了,有兴趣的可以看原文,篇头有链接。

  • 相关阅读:
    https 适配
    SDWebImage 的简单使用方法
    第三方API使用的好习惯
    关于IPicture::Render函数
    标准模板库(STL)MAP容器使用详解
    STL容器
    c++ 遍历map的时候删除元素
    C++的try_catch异常
    Makefile 自动生成头文件的依赖关系 .
    调试过程中,内存泄露检测信息
  • 原文地址:https://www.cnblogs.com/rader/p/2210057.html
Copyright © 2011-2022 走看看