多生產者多消費者問題

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ConsoleApplication1
{
    class Class1
    {
        private static Semaphore empty, full, mutex;
        private static int count = 0;
        static void Main(string[] args)
        {
            empty = new Semaphore(4, 4);
            full = new Semaphore(0, 4);
            mutex = new Semaphore(1, 1);
            Thread[] Pro = new Thread[10];
            Thread[] Co = new Thread[10];
            for (int i = 0; i < 10; i++)
            {
                Pro[i] = new Thread(productor); Pro[i].Start();
                Co[i] = new Thread(Consumer); Co[i].Start();
            }
        }
        public static void productor()
        {
            while (true)
            {
                empty.WaitOne();
                mutex.WaitOne();
                Console.WriteLine(++count);
                Thread.Sleep(1000);
                mutex.Release();
                full.Release();
            }
        }
        public static void Consumer()
        {
            while (true)
            {
                full.WaitOne();
                mutex.WaitOne();
                Console.WriteLine(--count);
                Thread.Sleep(1000);
                mutex.Release();
                empty.Release();
            }
            
        }

    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章