본문 바로가기
.Net

.NET - Semaphore 초기값? initialCount, maximumCount

by 올엠 2020. 12. 1.
반응형

Semaphore는 기본적으로 자원을 공유해서 사용해야 하는 멀트 스레드 환경에서 사용된다.

자원이나 실행에 대한 접근 제어가 필요할 때 사용할 수 있다.

.NET 기준으로 lock 개념과 유사하며, 큰 차이점이라면, lock은 하나의 접근만 가능하지만, Semaphore는 지정한 개수만큼 접근할 수 있다.

이 지정한 개수는 Semaphore를 선언시점에 기본적으로 2가지 값을 설정해 주어야 한다.

initialCount, maximumCount 이다.

maximumCount 는 최대 접근 가능 개수 라고 할 수 있다. 만약 maximumCount를 3으로 지정한 경우 3개의 까지의 접근을 허용 한다는 것이다.

그리고 initialCount는 Semaphore를 선언하는 시점에 사용가능한 갯수라고 생각하면 좋겠다. 

만약 0으로 선언하면, Semaphore 시작 시점에 전부 lock 상태로 시작하게 된다. 따라서 Release 를 통해 lock을 풀어주어야 한다.

 

 

using System;
using System.Threading;

namespace Semaphoretest
{
    class Program
    {
        private static Semaphore _semaphore;
        static void Main(string[] args)
        {
            // 세미포어 3개를 지정하고 0을 초기값으로 하여 현재 사용 가능한 세미포어는 없다.
            _semaphore = new Semaphore(0, 3);
            

            for (int i = 1; i <= 10; i++)
            {
                Thread t = new Thread(new ParameterizedThreadStart(Worker));
                t.Start(i);
            }
            Thread.Sleep(1000);

            Console.WriteLine("If you press to number 1-3, and Enter for Release to semaphore");
            string numberString = Console.ReadLine();
            int number = Convert.ToInt32(numberString);
            _semaphore.Release(number);
            

        }

        private static void Worker(object num)
        {            

            Console.WriteLine("Thread {0} begins and waits for the semaphore.", num);
            // 현재 사용 가능한 자원이 있는 확인하여 있다면 진입
            _semaphore.WaitOne();


            Console.WriteLine("Thread {0} enters the semaphore.", num);

            Thread.Sleep(1000);

            Console.WriteLine("Thread {0} releases the semaphore. semaphore count: {1}", num, _semaphore.Release());
            
        }
    }
}

 

 

 

 

 

 

참고

https://docs.microsoft.com/ko-kr/dotnet/api/system.threading.semaphore?view=netcore-3.1

 

Semaphore 클래스 (System.Threading)

리소스 또는 리소스 풀에 동시에 액세스할 수 있는 스레드 수를 제한합니다.Limits the number of threads that can access a resource or pool of resources concurrently.

docs.microsoft.com

 

반응형