세마포어 클래스를 사용하면 임계 섹션에 액세스할 수 있는 스레드 수에 대한 제한을 설정할 수 있습니다. 클래스는 리소스 풀에 대한 액세스를 제어하는 데 사용됩니다. System.Threading.Semaphore는 Semaphore를 구현하는 데 필요한 모든 메서드와 속성을 가지고 있기 때문에 Semaphore의 네임스페이스입니다.
C#에서 세마포어를 사용하려면 Semaphore 개체의 인스턴스를 인스턴스화하기만 하면 됩니다. 최소 두 개의 인수가 있습니다 -
참조
-
MSDN
| 시니어 번호 | 생성자 및 설명 |
|---|---|
| 1 | 세마포어(Int32,Int32) 초기 항목 수와 최대 동시 항목 수를 지정하여 Semaphore 클래스의 새 인스턴스를 초기화합니다. |
| 2 | 세마포어(Int32,Int32,String) - 초기 항목 수와 최대 동시 항목 수를 지정하고 선택적으로 시스템 세마포 개체의 이름을 지정하여 Semaphore 클래스의 새 인스턴스를 초기화합니다. |
| 3 | 세마포어(Int32,Int32,String,Boolean) 초기 항목 수와 최대 동시 항목 수를 지정하고 선택적으로 시스템 세마포 개체의 이름을 지정하고 새 시스템 세마포가 생성되었는지 여부를 나타내는 값을 받는 변수를 지정하여 Semaphore 클래스의 새 인스턴스를 초기화합니다. |
이제 예를 살펴보겠습니다.
여기에서 Semaphore 클래스의 새 인스턴스를 초기화하는 다음 Semaphore 생성자를 사용하여 최대 동시 항목 수를 지정하고 선택적으로 일부 항목을 예약했습니다.
static Semaphore semaphore = new Semaphore(2, 2);
예
using System;
using System.Threading;
namespace Program
{
class Demo
{
static Thread[] t = new Thread[5];
static Semaphore semaphore = new Semaphore(2, 2);
static void DoSomething()
{
Console.WriteLine("{0} = waiting", Thread.CurrentThread.Name);
semaphore.WaitOne();
Console.WriteLine("{0} begins!", Thread.CurrentThread.Name);
Thread.Sleep(1000);
Console.WriteLine("{0} releasing...", Thread.CurrentThread.Name);
semaphore.Release();
}
static void Main(string[] args)
{
for (int j = 0; j < 5; j++)
{
t[j] = new Thread(DoSomething);
t[j].Name = "thread number " + j;
t[j].Start();
}
Console.Read();
}
}
} 출력
다음은 출력입니다.
thread number 2 = waiting thread number 0 = waiting thread number 3 = waiting thread number 1 = waiting thread number 4 = waiting thread number 2 begins! thread number 1 begins! thread number 2 releasing... thread number 1 releasing... thread number 4 begins! thread number 3 begins! thread number 4 releasing... thread number 0 begins! thread number 3 releasing... thread number 0 releasing...