c#线程实现生产者消费者

public interface IThreadWorker : IDisposable
    {
        void RealWorker();
    }

    public class ThreadController
    {
        private Queue<IThreadWorker> WorkQueue = new Queue<IThreadWorker>();
        private int mMaxThreadCount = 5;
        private ManualResetEvent[] mCustomerSyncEvents = null;
        private ManualResetEvent[] mCustomerFinishEvents = null;
        public ManualResetEvent ProducterFinishEvent = new ManualResetEvent(false);
        private string ThreadName = string.Empty;
        //private bool Started = false;

        public ThreadController()
            : this(5, string.Empty)
        { }

        public ThreadController(int maxThreadCount)
            : this(maxThreadCount, string.Empty)
        { }

        public ThreadController(int maxThreadCount, string name)
        {
            ThreadName = name;
            mMaxThreadCount = maxThreadCount;
            mCustomerSyncEvents = new ManualResetEvent[maxThreadCount];
            mCustomerFinishEvents = new ManualResetEvent[maxThreadCount];
            for (int i = 0; i < maxThreadCount; i++)
            {
                mCustomerSyncEvents[i] = new ManualResetEvent(true);
                mCustomerFinishEvents[i] = new ManualResetEvent(false);
            }
            StartRun();
        }

        public void AddJobQueue(IThreadWorker info)
        {
            lock (((ICollection)WorkQueue).SyncRoot)
            {
                WorkQueue.Enqueue(info);
            }
            //if (!Started)
            //{
            //    StartRun();
            //    Started = true;
            //}
        }

        private void StartRun()
        {
            for (int i = 0; i < mMaxThreadCount; i++)
            {
                CustomerSyncEventController sync = new CustomerSyncEventController(mCustomerSyncEvents[i], mCustomerFinishEvents[i], ProducterFinishEvent);
                Thread thread = new Thread(new ParameterizedThreadStart(RealWork));
                thread.Start(sync);
            }
        }

        public bool Completed()
        {
            return WaitHandle.WaitAll(mCustomerFinishEvents);
        }

        private void RealWork(object obj)
        {
            CustomerSyncEventController sync = obj as CustomerSyncEventController;

            while (sync.CustomerSyncEvent.WaitOne())
            {
                sync.CustomerSyncEvent.Reset();
                try
                {
                    IThreadWorker instance = null;
                    if (sync.ProducterFinishEvent.WaitOne(10, true))
                    {
                        lock (((ICollection)WorkQueue).SyncRoot)
                        {
                            if (WorkQueue.Count == 0)
                            {
                                //Console.WriteLine("{0}, set", sync.i);
                                sync.CustomerFinishEvent.Set();
                                break;
                            }
                            else
                            {
                                instance = WorkQueue.Dequeue();
                            }
                        }
                    }
                    else
                    {
                        // Console.WriteLine("{0}, false", sync.i);
                        lock (((ICollection)WorkQueue).SyncRoot)
                        {
                            if (WorkQueue.Count == 0)
                            {
                                //break;
                            }
                            else
                            {
                                instance = WorkQueue.Dequeue();
                            }
                        }

                    }
                    using (instance)
                    {
                        //Console.WriteLine("{0}, {1}", sync.i, info.info);
                        instance.RealWorker();
                    }
                }
                catch (Exception e)
                {
                }
                finally
                {
                    //Console.WriteLine("{0}, set", sync.i);
                    sync.CustomerSyncEvent.Set();
                }
            }

        }

        internal class CustomerSyncEventController
        {
            public ManualResetEvent CustomerSyncEvent { get; set; }
            public ManualResetEvent CustomerFinishEvent { get; set; }
            public ManualResetEvent ProducterFinishEvent { get; set; }
            public CustomerSyncEventController()
            {
                CustomerSyncEvent = new ManualResetEvent(false);
                CustomerFinishEvent = new ManualResetEvent(false);
                ProducterFinishEvent = new ManualResetEvent(true);
            }
            public CustomerSyncEventController(ManualResetEvent customerSync, ManualResetEvent customerFinish, ManualResetEvent producterFinish)
            {
                CustomerSyncEvent = customerSync;
                CustomerFinishEvent = customerFinish;
                ProducterFinishEvent = producterFinish;
            }
        }
    }


 

public class ImplementClass : IThreadWorker
    {
        public string Content { get; set; }
        public ImplementClass(string content)
        {
            Content = content;
        }

        #region IThreadWorker Members

        public void RealWorker()
        {
            Console.WriteLine(Content);
        }

        #endregion

        #region IDisposable Members

        public void Dispose()
        {
        }

        #endregion
    }


 

static void Main(string[] args)
        {
            List<ImplementClass> list = new List<ImplementClass>();
            for (int i = 0; i <= 100; i++)
            {
                list.Add(new ImplementClass(i.ToString()));
            }
            ThreadController monitor = new ThreadController(32);
            foreach (ImplementClass ic in list)
            {
                monitor.AddJobQueue(ic);
            }
            monitor.ProducterFinishEvent.Set();
            if (monitor.Completed())
            { }
            
        }

实现自己的IThreadWorker,

不要忘记调用

monitor.ProducterFinishEvent.Set(),证明队列中不会再增加新的内容

monitor.Completed()保证所有的消费者都完成了工作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
生产者消费者问题是一个经典的多线程问题,其中有一个生产者线程和多个消费者线程共同操作一个共享的队列,生产者线程向队列中添加元素,消费者线程从队列中取出元素进行处理。为了避免竞争条件和死锁等问题,需要在程序中采用一些同步机制。下面是一个基于C#语言实现生产者消费者实验: ```csharp using System; using System.Threading; public class Program { private static Queue<int> queue = new Queue<int>(10); //定义一个大小为10的队列 private static object lockObj = new object(); //定义一个锁对象 static void Main(string[] args) { Thread producerThread = new Thread(new ThreadStart(Producer)); Thread[] consumerThreads = new Thread[5]; for (int i = 0; i < 5; i++) { consumerThreads[i] = new Thread(new ThreadStart(Consumer)); consumerThreads[i].Start(); } producerThread.Start(); } static void Producer() { while (true) { lock (lockObj) { if (queue.Count < 10) { int num = new Random().Next(100); queue.Enqueue(num); //向队列中添加元素 Console.WriteLine("生产者线程:{0} 生产了一个元素 {1},队列中元素个数为{2}", Thread.CurrentThread.ManagedThreadId, num, queue.Count); } else { Monitor.Wait(lockObj); //如果队列已满,生产者线程进入等待状态 } } Thread.Sleep(1000); Monitor.PulseAll(lockObj); //通知所有等待的线程有新的元素加入队列 } } static void Consumer() { while (true) { lock (lockObj) { if (queue.Count > 0) { int num = queue.Dequeue(); //从队列中取出元素 Console.WriteLine("消费者线程:{0} 消费了一个元素 {1},队列中元素个数为{2}", Thread.CurrentThread.ManagedThreadId, num, queue.Count); } else { Monitor.Wait(lockObj); //如果队列为空,消费者线程进入等待状态 } } Thread.Sleep(1000); Monitor.PulseAll(lockObj); //通知所有等待的线程有新的空位可供添加元素 } } } ``` 在这个实现中,我们使用了一个 `Queue<int>` 类型的队列来保存元素,使用了一个 `lockObj` 对象作为锁对象。生产者线程通过 `Monitor.Wait()` 进入等待状态,直到队列不为空;消费者线程通过 `Monitor.Wait()` 进入等待状态,直到队列不为满。在向队列中添加或者移除元素时,通过 `lock` 语句块保证对队列的访问是原子操作。在添加或移除元素后,我们通过 `Monitor.PulseAll()` 方法通知所有正在等待的线程有新的元素或空位可供操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值