How to create Own Semaphore?


 class CustomSemaphore
    {
        private Mutex[] arrMutex;

        // place holder to store thread to mutex mapping
        private Thread[] arrthread;

        // number of threads allowed to access the resources
        private int threadLimit;

        // contructor creates the mutexes
        public CustomSemaphore(int threadLimit)
        {
            this.threadLimit = threadLimit;
            arrMutex = new Mutex[this.threadLimit];
            arrthread = new Thread[this.threadLimit];
            for (int i = 0; i < this.threadLimit; i++)
            {
                arrMutex[i] = new Mutex();
                arrthread[i] = null;
            }
        }
        public int Wait()
        {
            int index = WaitHandle.WaitAny(arrMutex);
            if (index != WaitHandle.WaitTimeout)
                arrthread[index] = Thread.CurrentThread;
            return index;
        }
        public void Release()
        {
            for (int i = 0; i < threadLimit; i++)
            {
                if (arrthread[i] == Thread.CurrentThread)
                {
                    arrMutex[i].ReleaseMutex();
                    break;
                }
            }
        }
    }

Comments