生产者消费者实现代码

来源:互联网 发布:nginx for linux下载 编辑:程序博客网 时间:2024/05/08 10:38

       在操作系统中生产者消费者是一个重要的模型,这个概念很早就知道,但怎么实现它,却一直没找到相关代码,于是就自己查找相关资料,自己研究,终于写出了多线程相关的代码,之前研究过很多次,犯过很多错误,感觉很难,每次写的都在运行时间一长就有问题,但当写出来后,反倒不感觉有什么难度了。有兴趣研究多线程的朋友,不妨修改下,看看多线程时如何运行的。

      修改一下线程数量,看看多线程如何运行,调整一下信号量的位置,初始值,移动一下WaitOne,Release,看看如何使用信号量,去掉同步,看看死锁如何产生。

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;namespace ProducerConsumerModel{    class Program    {        private static int MaxCount = 10;//最大可以生产的产品数量        private static int currentCount = 0;//当前产品数量        private static Mutex mutex = new Mutex ();//同步量        private static Semaphore semaphoreConsumer = null;//消费者信号量        private static Semaphore semaphoreProducer = null;//生产者信号量        static void Main(string[] args)        {            semaphoreConsumer = new Semaphore(10, 10);//初始化消费者信号量            semaphoreProducer = new Semaphore(0, 10);//初始化生产者信号量            try              {                             for (int i = 1; i <= 5; i++)                {                    Thread t = new Thread(new ParameterizedThreadStart(minusProduct));                    t.Name = "Consumer" + i;                    t.Start(i);//初始化消费者                }                for (int i = 1; i <= 15; i++)                {                    Thread t = new Thread(new ParameterizedThreadStart(AddProduct));                    t.Name = "Producer" + i;                                   t.Start(i);//初始化生产者                }            }            catch (Exception e) {                Console.WriteLine(e.Message);            }            System.Console.ReadLine();        }        /// <summary>        /// 生产者生产产品        /// </summary>        /// <param name="num"></param>        private static void AddProduct(object num)         {            while (true)            {                Console.WriteLine("Thread {0} begins " +                "and waits for the semaphore..currentCount is {1}", Thread.CurrentThread.Name, currentCount);                             semaphoreProducer.WaitOne();//先等待消费者发过来的信号量                if (currentCount > MaxCount)                {                    Console.WriteLine("Thread {0} enters the semaphore..currentCount is {1},is full", Thread.CurrentThread.Name, currentCount);                                  }                else                {                    Console.WriteLine("Thread {0} enters the semaphore..currentCount is {1}", Thread.CurrentThread.Name, currentCount);                    mutex.WaitOne();//同步数据                  //  Interlocked.Increment(ref currentCount);                    currentCount++;                    mutex.ReleaseMutex();//                    Console.WriteLine("Thread {0} releases the semaphore..currentCount is {1}", Thread.CurrentThread.Name, currentCount);                                   }                semaphoreConsumer.Release();//通知消费者                Console.WriteLine("Thread {0} leave out AddProduct " +                   ".currentCount is {1}", Thread.CurrentThread.Name, currentCount);                Random r = new Random();//模拟比较花费时间的操作,制造线程切换                int second = r.Next(1, 1000);                Thread.Sleep(second);                      }        }        /// <summary>        ///  消费者消费产品        /// </summary>        /// <param name="num"></param>        private static void minusProduct(object num)        {            while (true)            {                Console.WriteLine("Thread {0} begins " +                "and waits for the semaphore.currentCount is{1}", Thread.CurrentThread.Name, currentCount);                             semaphoreConsumer.WaitOne();//等待生产者的信号量                                if (currentCount < 1)                {                    Console.WriteLine("Thread {0} enters the semaphore..currentCount is{1},is empty", Thread.CurrentThread.Name, currentCount);                                     }                else                {                    Console.WriteLine("Thread {0} enters the semaphore.currentCount is{1}", Thread.CurrentThread.Name, currentCount);                    mutex.WaitOne();//  同步数据                             //  Interlocked.Decrement(ref currentCount);                    currentCount--;                    mutex.ReleaseMutex();//                    Console.WriteLine("Thread {0} releases the semaphore.currentCount is{1}", Thread.CurrentThread.Name, currentCount);                  //                }                semaphoreProducer.Release();//通知生产者                Console.WriteLine("Thread {0} leave out minusProduct " +                    ".currentCount is {1}", Thread.CurrentThread.Name, currentCount);                Random r = new Random();//模拟比较花费时间的操作,制造线程切换                int second = r.Next(1, 1000);                Thread.Sleep(second);            }        }    }}







原创粉丝点击