본문 바로가기
C#/책 예제

C# Thread Monitor.Wait 그리고 Monitor.Pulse 사용하기

by HyunS_ 2019. 6. 8.
using System;
using System.Threading;

namespace ThreadNTask
{
    class Program
    {
        static void Main(string[] args)
        {
            Counter counter = new Counter();

            Thread increaseThread = new Thread(new ThreadStart(counter.Increase));
            Thread decreaseThread = new Thread(new ThreadStart(counter.Decrease));

            increaseThread.Start();
            decreaseThread.Start();

            increaseThread.Join();
            decreaseThread.Join();

            Console.WriteLine(counter.Count);

        }
    }

    class Counter
    { 
        const int LOOP_COUNT = 1000;

        readonly object thisLock;
        bool lockedCount = false;

        private int count;
        
        public int Count
        { 
            get{ return count; }
        }

        public Counter()
        { 
            thisLock = new object();
            count = 0;
        }

        public void Increase()
        { 
            int loopCount = LOOP_COUNT;
            while(loopCount-- > 0)
            {
                lock(thisLock)
                {
                    while(count < 0 || lockedCount == true)
                    {
                        Monitor.Wait(thisLock);
                        lockedCount = true;
                        count ++;
                        lockedCount = false;

                        Monitor.Pulse(thisLock);
                    }
                }
            }
        }

        public void Decrease()
        { 
            int loopCount = LOOP_COUNT;

            while (loopCount-- > 0)
            {
                lock (thisLock)
                {
                    while (count < 0 || lockedCount == true)
                    {
                        Monitor.Wait(thisLock);
                        lockedCount = true;
                        count++;
                        lockedCount = false;

                        Monitor.Pulse(thisLock);
                    }
                }
            }
        }
    }
}
728x90

댓글