C#에서 여러 스레드 간에 통신하고 동기화하기 위해서는 스레드 간에 신호를 전달해야 합니다. 스레드 신호는 다른 스레드에 대한 상태 변화나 작업 완료를 알리기 위해 사용됩니다. C#에서는 ManualResetEvent
및 AutoResetEvent
와 같은 클래스를 사용하여 스레드 간에 신호를 전달하고 동기화할 수 있습니다.
ManualResetEvent와 AutoResetEvent
ManualResetEvent
와 AutoResetEvent
는 System.Threading 네임스페이스에서 제공되는 클래스로, 스레드 간에 신호를 주고 받을 수 있게 해줍니다. 두 클래스 모두 이벤트 객체를 기반으로 동작하며, 스레드가 작업을 완료하거나 특정 조건이 충족될 때 이벤트를 발생시킵니다.
ManualResetEvent
ManualResetEvent
는 모든 대기 중인 스레드에게 신호를 보낼 때까지 이벤트 상태를 유지합니다. 한 번 신호를 보내면, 모든 스레드가 작업을 계속할 수 있습니다.
ManualResetEvent
의 예시 코드는 다음과 같습니다:
using System;
using System.Threading;
public class Example
{
private ManualResetEvent _manualEvent = new ManualResetEvent(false);
public void Thread1()
{
Console.WriteLine("Thread 1 is running.");
Thread.Sleep(1000);
_manualEvent.Set(); // Send signal
}
public void Thread2()
{
Console.WriteLine("Thread 2 is waiting.");
_manualEvent.WaitOne(); // Wait for signal
Console.WriteLine("Thread 2 received the signal and is running.");
}
}
AutoResetEvent
AutoResetEvent
는 한 번 신호를 보내면 하나의 대기 중인 스레드에게만 신호를 보내고 자동으로 이벤트 상태를 재설정합니다.
AutoResetEvent
의 예시 코드는 다음과 같습니다:
using System;
using System.Threading;
public class Example
{
private AutoResetEvent _autoEvent = new AutoResetEvent(false);
public void Thread1()
{
while (true)
{
Console.WriteLine("Thread 1 is running.");
Thread.Sleep(1000);
_autoEvent.Set(); // Send signal
}
}
public void Thread2()
{
while (true)
{
Console.WriteLine("Thread 2 is waiting.");
_autoEvent.WaitOne(); // Wait for signal
Console.WriteLine("Thread 2 received the signal and is running.");
}
}
}
위의 예시 코드에서는 ManualResetEvent
와 AutoResetEvent
를 사용하여 각각 두 개의 스레드 간에 신호를 보내고 받는 방법을 보여주고 있습니다.
C#에서 이러한 클래스를 사용하여 다중 스레드 프로그래밍을 할 때에는 명확하고 안전한 방법으로 스레드 간에 통신하고 동기화할 수 있습니다.
참고 자료
- Microsoft 문서: ManualResetEvent Class
- Microsoft 문서: AutoResetEvent Class