본문 바로가기
.NET

AutoResetEvent Class 샘플 예제 분석

by leo21c 2023. 10. 24.
SMALL

AutoResetEvent(Boolean) 생성자 (System.Threading) | 마이크로소프트 런 (microsoft.com)

 

AutoResetEvent(Boolean) Constructor (System.Threading)

Initializes a new instance of the AutoResetEvent class with a Boolean value indicating whether to set the initial state to signaled.

learn.microsoft.com

신호를 받으면 대기 중인 단일 스레드를 해제한 후 자동으로 다시 설정되는 스레드 동기화 이벤트

(A thread synchronization event that, when signaled, resets automatically after releasing a single waiting thread.)

public AutoResetEvent (bool initialState);
Parameters :  Boolean initialState 
true to set the initial state to signaled; false to set the initial state to non-signaled.

아래 예제는 ReaderThread를 생성하고 시작을 한다.

for 루프를 돌면서 number에 i 값을 넣고 myResetEvent.Set();을 호출해서 Thread에 myResetEvent.WaitOne();을 이용해서 Blocking 되어 있는 것을 해제 한다.


using System;
using System.Threading;

namespace AutoResetEvent_Examples
{
    class MyMainClass
    {
        //Initially not signaled.
      const int numIterations = 100;
      static AutoResetEvent myResetEvent = new AutoResetEvent(false);
      static int number;
      
      static void Main()
        {
         //Create and start the reader thread.
         Thread myReaderThread = new Thread(new ThreadStart(MyReadThreadProc));
         myReaderThread.Name = "ReaderThread";
         myReaderThread.Start();

         for(int i = 1; i <= numIterations; i++)
         {
            Console.WriteLine("Writer thread writing value: {0}", i);
            number = i;
            
            //Signal that a value has been written.
            myResetEvent.Set();//Set 함수를 호출하면 Thread의 WaitOne()이 해제 되어 넘어간다.
            
            //Give the Reader thread an opportunity to act.
            Thread.Sleep(1);
         }

         //Terminate the reader thread.
         myReaderThread.Abort();
      }

      static void MyReadThreadProc()
      {
         while(true)
         {
            //The value will not be read until the writer has written
            // at least once since the last read.
            myResetEvent.WaitOne();//위의 Main()함수에서 Set이 호출될 때 lock이 해제 된다.
            Console.WriteLine("{0} reading value: {1}", Thread.CurrentThread.Name, number);
         }
      }
    }
}

AutoResetEvent는 WaitOne() 함수로 Lock을 하고 Set() 함수로 Unlock 처리 하는 이벤트이다.

LIST