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

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로 바꾸는 작업을 했겠지요?

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




전경/배경 스레드 테스트 코드

#include <thread>
#include <iostream>
#include <unistd.h>
#include <pthread.h>

#define USE_STL

void* threadFunc(void* arg)
{
    sleep(5);
    std::cout << "Hello from thread!" << std::endl;
    return NULL;
}

int main()
{
#if defined(USE_STL)
    std::thread t([&]() {

        sleep(5);
        std::cout << "Hello from thread!" << std::endl;
    });

    t.detach();
#else
    pthread_t tid;
    pthread_create(&tid, NULL, threadFunc, NULL);
#endif

    pthread_exit(nullptr);

    return 0;
}

#include <thread>
#include <iostream>
#include <Windows.h>

DWORD threadFunc(void* arg)
{
    Sleep(5000);
    std::cout << "Hello from thread!" << std::endl;
    return 0;
}

int main()
{
#if defined(USE_STL)
    std::thread t([&]() {

        Sleep(5 * 1000);
        std::cout << "Hello from thread!" << std::endl;
    });

    t.detach();
#else
    CreateThread(nullptr, 0, threadFunc, nullptr, 0, nullptr);
#endif

    ExitThread(0);
    return 0;
}



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

[연관 글]






[최초 등록일: ]
[최종 수정일: 8/26/2024]

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)
13641정성태6/11/20248661Linux: 71. Ubuntu 20.04를 22.04로 업데이트
13640정성태6/10/20248833Phone: 21. C# MAUI - Android 환경에서의 파일 다운로드(DownloadManager)
13639정성태6/8/20248443오류 유형: 906. C# MAUI - Android Emulator에서 "Waiting For Debugger"로 무한 대기
13638정성태6/8/20248524오류 유형: 905. C# MAUI - 추가한 layout XML 파일이 Resource.Layout 멤버로 나오지 않는 문제
13637정성태6/6/20248447Phone: 20. C# MAUI - 유튜브 동영상을 MediaElement로 재생하는 방법
13636정성태5/30/20248089닷넷: 2264. C# - 형식 인자로 인터페이스를 갖는 제네릭 타입으로의 형변환파일 다운로드1
13635정성태5/29/20248940Phone: 19. C# MAUI - 안드로이드 "Share" 대상으로 등록하는 방법
13634정성태5/24/20249416Phone: 18. C# MAUI - 안드로이드 플랫폼에서의 Activity 제어 [1]
13633정성태5/22/20248945스크립트: 64. 파이썬 - ASGI를 만족하는 최소한의 구현 코드
13632정성태5/20/20248562Phone: 17. C# MAUI - Android 내에 Web 서비스 호스팅
13631정성태5/19/20249322Phone: 16. C# MAUI - /Download 등의 공용 디렉터리에 접근하는 방법 [1]
13630정성태5/19/20248866닷넷: 2263. C# - Thread가 Task보다 더 빠르다는 어떤 예제(?)
13629정성태5/18/20249163개발 환경 구성: 710. Android - adb.exe를 이용한 파일 전송
13628정성태5/17/20248542개발 환경 구성: 709. Windows - WHPX(Windows Hypervisor Platform)를 이용한 Android Emulator 가속
13627정성태5/17/20248606오류 유형: 904. 파이썬 - UnicodeEncodeError: 'ascii' codec can't encode character '...' in position ...: ordinal not in range(128)
13626정성태5/15/20248873Phone: 15. C# MAUI - MediaElement Source 경로 지정 방법파일 다운로드1
13625정성태5/14/20248929닷넷: 2262. C# - Exception Filter 조건(when)을 갖는 catch 절의 IL 구조
13624정성태5/12/20248722Phone: 14. C# - MAUI에서 MediaElement 사용파일 다운로드1
13623정성태5/11/20248418닷넷: 2261. C# - 구글 OAuth의 JWT (JSON Web Tokens) 해석파일 다운로드1
13622정성태5/10/20249206닷넷: 2260. C# - Google 로그인 연동 (ASP.NET 예제)파일 다운로드1
13621정성태5/10/20248637오류 유형: 903. IISExpress - Failed to register URL "..." for site "..." application "/". Error description: Cannot create a file when that file already exists. (0x800700b7)
13620정성태5/9/20248547VS.NET IDE: 190. Visual Studio가 node.exe를 경유해 Edge.exe를 띄우는 경우
13619정성태5/7/20248860닷넷: 2259. C# - decimal 저장소의 비트 구조파일 다운로드1
13618정성태5/6/20248654닷넷: 2258. C# - double (배정도 실수) 저장소의 비트 구조파일 다운로드1
13617정성태5/5/20249471닷넷: 2257. C# - float (단정도 실수) 저장소의 비트 구조파일 다운로드1
13616정성태5/3/20248618닷넷: 2256. ASP.NET Core 웹 사이트의 HTTP/HTTPS + Dual mode Socket (IPv4/IPv6) 지원 방법파일 다운로드1
1  2  3  4  5  6  7  8  9  10  11  [12]  13  14  15  ...