본문 바로가기

운동하는 개발자/Delphi

델파이 크리티컬세션 사용법 / delphi criticalsection (for multiThread)

728x90

멀티스레드의 환경을 개발하는 경우 여러 쓰레드가 같은 파일에 접근하거나 상태 값, 인덱스 값 등을 갱신/읽기 하려는 경우가 많이 있다 이때 자칫하다간 원하는 대로 동작하지 않거나 access violation이 발생하기도 한다
이를 방지하기 위해 동시에 접근하는 메모리,변수 등에 크리티컬섹션을 걸어서 충돌을 방지하자

 

선언부

uses 
  windows;
 
var
  CriticalSection: TRTLCriticalSection;

~~~~~~~~~
~~class~~  
~~~~~~~~~  
  
initialization
  InitializeCriticalSection(CriticalSection);
    
finalization
  DeleteCriticalSection(CriticalSection);

 

사용부분

workSum : Integer; //여러 스레드가 동시에 접근 할 변수



//Thread1
while(True) do
begin
  work()
  
  EnterCriticalSection(CriticalSection);  //진입시 leave가 호출되기전까지 대기함
  try		//크리티컬 세션 내에서 exception 발생시 락 방지(except와 finally 필수)
    worksum += 2;
  finally
    LeaveCriticalSection(CriticalSection);
  end;
end;


//Thread2
while(True) do
begin
  work()
  EnterCriticalSection(CriticalSection);  
  try		
    worksum += 1;
  finally
    LeaveCriticalSection(CriticalSection);
  end;  
end;

 

참고사항

  • 주석에 적었듯이 크리티컬섹션 내부에서 exception이 발생하거나 exit 등으로 빠져나가는 경우 무한 락이 걸릴 수 있다 꼭 try except, try finally를 이용해서 leave함수를 타도록 하자
  • enter가 되지 않은 상태에서 leave호출 시에도 에러가 발생한다(비교적 찾기도 쉽고 발생도 드물다)
  • 여러 유닛에서 동시 사용해야 한다면 별도의 글로벌 유닛을 만들어서 거기서 선언해주는 것이 좋다
728x90