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

C# Thread Monitor 키워드를 이용한 동기화

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;

        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)
            {
                Monitor.Enter(thisLock);
                try
                {
                    count++;
                }
                finally
                { 
                    Monitor.Exit(thisLock);
                }
                Thread.Sleep(1);
            }
        }

        public void Decrease()
        { 
            int loopCount = LOOP_COUNT;

            while (loopCount-- > 0)
            {
                Monitor.Enter(thisLock);
                try
                {
                    count--;
                }
                finally
                {
                    Monitor.Exit(thisLock);
                }
                Thread.Sleep(1);
            }
        }
    }
}
728x90

댓글