목차
세마포어
세마포어는 동시에 리소스에 접근할 수 있는 스레드의 수를 제한합니다.
예를 들어, 동시에 5개의 스레드만이 특정 리소스에 접근할 수 있도록 하고 싶다면, 세마포어를 5로 설정할 수 있습니다. 스레드가 세마포어를 획득하면 내부 카운트가 감소하고, 스레드가 세마포어를 해제하면 카운트가 증가합니다. 카운트가 0이 되면, 다른 스레드는 세마포어를 획득할 때까지 대기해야 합니다.
C#에서의 세마포어
예를 들어, 게임 로비가 동시에 최대 10명의 플레이어만 수용할 수 있게 설정되어 있다고 가정해 보겠습니다.
using System;
using System.Threading;
using System.Collections.Generic;
public class GameLobby
{
private Semaphore semaphore;
private int maxPlayers;
public GameLobby(int maxPlayers)
{
this.maxPlayers = maxPlayers;
this.semaphore = new Semaphore(maxPlayers, maxPlayers);
}
public void EnterLobby(string playerName)
{
Console.WriteLine($"{playerName} is trying to enter the lobby...");
// Wait to enter the lobby
semaphore.WaitOne();
Console.WriteLine($"{playerName} has entered the lobby.");
// 여기서 플레이어 활동~
LeaveLobby(playerName);
}
public void LeaveLobby(string playerName)
{
Console.WriteLine($"{playerName} is leaving the lobby.");
// 세마포어 반환!
semaphore.Release();
Console.WriteLine($"{playerName} has left the lobby.");
}
}
class Program
{
static void Main(string[] args)
{
GameLobby lobby = new GameLobby(10); // 10개 최대로 설정
for (int i = 1; i <= 20; i++)
{
int playerNumber = i;
Thread playerThread = new Thread(() => lobby.EnterLobby($"Player {playerNumber}"));
playerThread.Start();
}
}
}
C#
복사
세마포어의 장단점
세마포어의 장점
1.
공유 리소스의 동시 접근 제어 : 세마포어는 공유 리소스에 동시에 접근할 수 있는 스레드의 수를 정확하게 제어할 수 있습니다.
세마포어의 단점
1.
소유권 부재: 세마포어는 소유권 개념이 없습니다. 즉, 세마포어를 획득한 스레드와 이를 해제하는 스레드가 다를 수 있습니다. 이는 프로그램의 논리적 오류를 초래할 수 있으며, 특히 뮤텍스와 같이 소유권이 중요한 상황에서 문제가 될 수 있습니다.
2.
자원 해제의 복잡성 : 세마포어를 사용할 때, 모든 스레드가 리소스 사용을 완료한 후에 세마포어를 올바르게 해제해야 합니다. 이 과정에서 오류가 발생하면, 리소스 누수나 다른 스레드의 대기 상태 지속과 같은 문제가 발생할 수 있습니다.