◆ 무한한 가능성/& Visual C/C++

Thread in C++> example code. - Thread05

치로로 2009. 8. 20. 11:51

Thread in C++> example code. - Thread05


//------------------------------------------------------------------------------
// C++의 Class를 이용한 스레드 예제 - 시작
//------------------------------------------------------------------------------

#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <process.h>
#include <assert.h>

#define ONEK 1024

typedef struct _SumInfo
{
 int a, b, s;
}SUMINFO, *PSUMINFO;

void WriteString(const char* lpszFormat, ...)
{
 char str[ONEK];
 va_list argList;
 va_start(argList, lpszFormat);
 vprintf(lpszFormat, argList);
 va_end(argList);
}

// 우선 클래스 객체를 생성한 후, CMyThread::CreateThread를
// 호출하면, 스레드 루틴(Sum)이 실행을 시작한다.
class CMyThread
{
public:
 CMyThread(LPVOID p=NULL) : m_lpParam(p), m_hThread(0) {}
 virtual ~CMyThread() { CloseHandle(m_hThread); }
 void Delete() { if(m_AutoDelete) delete this; }
    int CreateThread()
 {
  unsigned addr;
  m_hThread = (void*)_beginthreadex(NULL, 0, Sum, this, 0, &addr);
  assert(m_hThread);
  return 0;
 }
 static unsigned __stdcall Sum(void* p)
 {
  // 스레드 함수 인자로 객체 포인터를 받음
  CMyThread *c = (CMyThread*) p;
  PSUMINFO psi = (PSUMINFO) c->m_lpParam;
  do {
   psi->s += psi->a;
   Sleep(20);
  }while(psi->a++ != psi->b);
  printf("\nSum결과 %d\n", psi->s);
  c->Delete();
  _endthreadex(0);
  return 0;
 };

 HANDLE m_hThread;
 LPVOID m_lpParam;
 BOOL m_AutoDelete;
};


void main()
{
 char temp[ONEK];
 DWORD dwExitCode;
 printf("*** 예제 [Thread05] C++ 클래스를 이용한 스레드 예제 *** \n");

 // 데이터 크기의 메모리 영역을 할당
 PSUMINFO psi = (PSUMINFO)malloc(sizeof(SUMINFO));
 psi->a = 1;
 psi->b = 100;
 psi->s = 0;

 SUMINFO si={1, 100, 0};

 // CMythread 객체를 생성한다.
 CMyThread *pMyThread = new CMyThread(&si);
 if(pMyThread == NULL)
  return;

 // 클래스의 멤버변수에 데이터를 입력
 pMyThread->m_AutoDelete = TRUE;

 // 실행 준비가 모두 되었으면, 스레드 함수 실행
 pMyThread->CreateThread();

 // 클래스가 소유한 스레드 루틴이 종료될 때까지 기다리면서
 // 0.02초 간격으로 "."을 화면에 찍는다.
 while (GetExitCodeThread(pMyThread->m_hThread, &dwExitCode))
 {
  if(dwExitCode != STILL_ACTIVE)
  {
   break;
  }
  else
  {
   WriteString(TEXT("."));
   Sleep(20);
  }
 }
 // 디버그용으로 화면이 사라지는 것을 막는다.
 scanf(temp);
 // 메인스레드가 종료된다.
 return;
}


//------------------------------------------------------------------------------
// C++의 Class를 이용한 스레드 예제 - 끝
//------------------------------------------------------------------------------