Microsoft MVP성태의 닷넷 이야기
.NET Framework: 91. Foreground Thread / Background Thread [링크 복사], [링크+제목 복사]
조회: 25640
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

Foreground Thread / Background Thread


마침 재미있는 글이 또 하나 떠서 ^^ 써봅니다.

메인 스레드가 종료되면 나머지 스레드도 종료될까?
; http://www.jiniya.net/tt/526

실제로 그렇지요. main thread라고 해서 특별한 것은 없습니다. 단지 해당 프로세스 공간의 Code Section을 긁고(!) 다니는 첫 번째 스레드일 뿐. (스레드라... 갑자기 안 좋은 기억이 떠오르는군요. 그 2명도... 어쩌면 "네이버 프로그래머"였을 지도.)

그런데, 닷넷에서 제공되는 Thread 클래스에는 재미있는 속성이 하나 있습니다. 바로 "IsBackgroundThread (read/write)"라는 속성입니다.

Foreground Thread와 Background Thread의 차이점은 단 하나입니다. Foreground Thread의 경우에는 아직 Running 상태에 있다면, 프로세스가 종료되는 것을 막는 반면, Background Thread의 경우에는 설령 동작 중이라 해도 프로세스의 종료를 막지 못합니다.

오호... 스레드에는 주종 관계가 없다고 위의 글에도 나와 있는데... 그렇다면 이를 어찌 설명해야 할까요?

그렇습니다. 닷넷의 "Managed" 환경은, 스레드까지도 잘 "관리"를 해주기 때문에 이런 것이 가능합니다. 이에 대한 대강의 해답을 찾기 위해서는... 역시나 "Shared Source CLR"을 참고하는 것이 좋겠습니다.

Shared Source Common Language Infrastructure 2.0 Release
; http://www.microsoft.com/downloads/details.aspx?FamilyId=8C09FD61-3F26-4555-AE17-3121B4F51D4D&displaylang=en

그럼, 단서가 되는 부분을 하나씩 검색해 볼까요?

"찾기"를 이용해서 우선 검색해 보아야 할 것이 "IsBackground"의 정의일 테죠! 오호... 검색해 보니 아래와 같이 나옵니다.

\sscli20\clr\src\bcl\system\threading\thread.cs

public bool IsBackground {
  get { return IsBackgroundNative(); }
  [HostProtection(SelfAffectingThreading=true)]
  set { SetBackgroundNative(value); }
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern bool IsBackgroundNative();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void SetBackgroundNative(bool isBackground);

차례로, "SetBackgroundNative"를 검색해 보면.

\sscli20\clr\src\vm\ecall.cpp

FCFuncStart(gThreadFuncs)
  FCFuncElement("SetBackgroundNative", ThreadNative::SetBackground)

결국 실제 정의는 "ThreadNative::SetBackground"에 있다는 것이고. 이를 또 검색해 보면.

\sscli20\clr\src\vm\comsynchronizable.cpp

FCIMPL2(void, ThreadNative::SetBackground, ThreadBaseObject* pThisUNSAFE, CLR_BOOL isBackground)
{
; 생략

  // validate the thread
  Thread  *thread = pThisUNSAFE->GetInternal();

; 생략

  thread->SetBackground(isBackground);

  HELPER_METHOD_FRAME_END();
}
FCIMPLEND

이렇게 Thread 클래스의 SetBackground 메서드에 isBackground 메서드를 전달하는 것으로 끝을 맺고 있습니다. 그렇다면 과연 SetBackground에서는 어떤 역할을 할까요?

\sscli20\clr\src\vm\threads.cpp

// Background threads must be counted, because the EE should shut down when the
// last non-background thread terminates.  But we only count running ones.
void Thread::SetBackground(BOOL isBack)
{
; 생략

  if (IsDead())
  {
  }
  else
  if (isBack)
  {
    if (!IsBackground())
    {
      FastInterlockOr((ULONG *) &m_State, TS_Background);

      // unstarted threads don't contribute to the background count
      if (!IsUnstarted())
        ThreadStore::s_pThreadStore->m_BackgroundThreadCount++;
    }
  }
  else
  {
; 생략
  }
}

자... "Thread::SetBackground" 함수까지 오니 이제서야 쓸만한 코드들이 나오기 시작합니다. 닷넷에서는, 명시적으로 IsBackground 값을 True로 지정하지 않는 한은 Foreground 스레드입니다. 따라서 isBack == TRUE이고 현재 Background 스레드가 아니면 s_pThreadStore->m_BackgroundThreadCount 값을 1 증가시켜 놓고 있습니다.

그렇다면, 간단한 상황이라고 가정하고 - 현재 어떤 스레드가 종료 중일 때 총 구동되고 있는 Managed Thread 수와 m_BackgroundThreadCount - 1의 수가 같은 상황이라면 주저없이 프로세스 종료를 해도 상관없다는 결론이 나옵니다. 즉, 닷넷의 CLR 호스팅 코드에서는 이러한 처리가 되어 있다는 것이겠지요.

예상 결과를 검증해 보기 위해 조금 더 검색을 해보면, CLR 종료를 할 수 있는 이벤트를 발생하는 다음과 같은 코드를 발견할 수 있습니다.

\sscli20\clr\src\vm\threads.cpp

void ThreadStore::CheckForEEShutdown()
{
; 생략

  if (g_fWeControlLifetime &&
      s_pThreadStore->OtherThreadsComplete())
  {
    BOOL bRet;
    bRet = s_pThreadStore->m_TerminationEvent.Set();
    _ASSERTE(bRet);
  }
}

아하... 예상이 맞아 들어갑니다. OtherThreadsComplete 조건이 TRUE가 되면 m_TerminationEvent 이벤트가 signal 되는군요. 잠시 OtherThreadsComplete 함수를 찾아보면,

\sscli20\clr\src\vm\threads.h

// Have all the foreground threads completed?  In other words, can we release
// the main thread?
BOOL        OtherThreadsComplete()
{
; 생략

  return (m_ThreadCount - m_UnstartedThreadCount - m_DeadThreadCount
          - Thread::m_ActiveDetachCount + m_PendingThreadCount
          == m_BackgroundThreadCount);
}

return 코드는 볼 것도 없이, ^^; 주석이 잘 말해주고 있습니다. 그렇다면, 이렇게 조건을 만족해서 m_TerminationEvent가 signal 된다면 어떤 코드가 실행이 되는 것일까요?

아래의 코드에서 그 해답을 찾을 수 있습니다.

\sscli20\clr\src\vm\threads.cpp

void ThreadStore::WaitForOtherThreads()
{
; 생략

  Thread      *pCurThread = GetThread();

; 생략

  if (!OtherThreadsComplete())
  {
    TSLockHolder.Release();

    FastInterlockOr((ULONG *) &pCurThread->m_State, Thread::TS_ReportDead);

    DWORD ret = WAIT_OBJECT_0;
    while (CLREventWaitWithTry(&m_TerminationEvent, INFINITE, TRUE, &ret))
    {
    }
    _ASSERTE(ret == WAIT_OBJECT_0);
  }
}

무한(INFINITE) 대기를 하고 있습니다. 만약 이 함수의 while 루프가 종료하게 되면... 아마도 당연히 CLR 호스팅이 종료하게 될 것입니다. 그래서 찾아보면 다음의 코드를 발견할 수 있습니다.

\sscli20\clr\src\vm\assembly.cpp

static void RunMainPost()
{

; 중간 생략

  GCX_PREEMP();
  ThreadStore::s_pThreadStore->WaitForOtherThreads();

#ifdef _DEBUG
  // Turn on memory dump checking in debug mode.
  _DbgRecord();
#endif
}

RunMainPost가 리턴하면, Assembly::ExecuteMainMethod가 종료하고, 이어서 SystemDomain::ExecuteMainMethod, ExecuteEXE, _CorExeMain2까지 이어지고, 결국 EEPolicy::HandleExitProcess를 호출하는 것으로 CLR 호스트 프로세스는 종료하게 됩니다.

오호... 그런데... 이 순서를 어디선가 본 기억이 나는 것 같습니다.
기억하시는 분이 계실래나? ^^

0:000> k
ChildEBP RetAddr  
0026ed70 79f9691a KERNEL32!RaiseException+0x58
0026edd0 7a098e88 mscorwks!RaiseTheExceptionInternalOnly+0x226
0026ee94 003e00a7 mscorwks!JIT_Throw+0xfc
WARNING: Frame IP not in any known module. Following frames may be wrong.
0026eeb0 79e826bd 0x3e00a7
0026ef30 79e8451b mscorwks!CallDescrWorkerWithHandler+0xa3
0026f06c 79e84403 mscorwks!MethodDesc::CallDescr+0x19c
0026f084 79e843e0 mscorwks!MethodDesc::CallTargetWorker+0x20
0026f098 79ef3e20 mscorwks!MethodDescCallSite::CallWithValueTypes+0x18
0026f1fc 79ef3c19 mscorwks!ClassLoader::RunMain+0x220
0026f464 79ef3aee mscorwks!Assembly::ExecuteMainMethod+0xa6
0026f934 79ef3737 mscorwks!SystemDomain::ExecuteMainMethod+0x398
0026f984 79ef18d1 mscorwks!ExecuteEXE+0x59
0026f9cc 79003aa0 mscorwks!_CorExeMain+0x11b
0026f9dc 76763833 mscoree!_CorExeMain+0x2c
0026f9e8 77c7a9bd KERNEL32!BaseThreadInitThunk+0xe
0026fa28 00000000 ntdll!_RtlUserThreadStart+0x23

기억이 안 나신다고요? ^^
다음의 토픽에서 설명했었습니다. (그나저나,,, windbg는 자주 사용을 안하다 보니 잊어버리게 되는군요. ^^;)

(Managed) Main Method에 Break Point 걸기
; https://www.sysnet.pe.kr/2/0/469

자꾸만 연상되는군요. 그러고 보니... SQLClr에서는 위의 호스팅 코드에서 사용되던 TLS도 모두 FLS로 바꾸는 작업을 했겠지요?

끝으로. 역시나,,, 이번에도 신영진 님 덕분에. ^^



[이 토픽에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/5/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2007-07-09 05시30분
[codewiz] 좋은 글 잘 읽고 갑니다.
안 좋은 기억 부분에서 피식하고 웃었습니다.
[guest]

[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13601정성태4/19/2024213닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/2024277닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024304닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024337닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드1
13597정성태4/15/2024404닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/2024779닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/2024904닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241017닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241050닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241207C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241169닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241073Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241143닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241197닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신파일 다운로드1
13587정성태3/27/20241156오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241297Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241096Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241048개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241158Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241420Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
13581정성태3/18/20241588개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
13580정성태3/15/20241137닷넷: 2231. C# - ReceiveTimeout, SendTimeout이 적용되지 않는 Socket await 비동기 호출파일 다운로드1
13579정성태3/13/20241494오류 유형: 899. HTTP Error 500.32 - ANCM Failed to Load dll
13578정성태3/11/20241629닷넷: 2230. C# - 덮어쓰기 가능한 환형 큐 (Circular queue)파일 다운로드1
13577정성태3/9/20241876닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx)
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...