월요일, 3월 24, 2008

Thread, Timer in a Class

정확히 원하는 것은 클래스 instance를 생성하면, 내부 타이머가 동작하여

자체 다이나믹스를 일정 시간 마다 업데이트 하는 것이었는데..

이렇게 하는게 정확하고 효율적인 방법인지는 모르겠다..일단 동작은 한다.

타이머의 정확도는 고려하지 않았음...

posix thread와 standard time library를 이용

instance의 초기화 함수인 initemotion이 호출되면 thread를 생성하고

thread는 instance에서 주어진 시간 간격으로 instance의 특정 함수를 호출하는 구조

상관 없는 코드는 모두 소거...

Header Emotion.h

#include "pthread.h"
#pragma comment(lib, "pthreadvc2.lib")

class CEmotion
{
public:
CEmotion();
virtual ~CEmotion();

pthread_t thread_timer;
void Timer();
void StopTimer();

double GetTimerStep() {return TimerStep;}
void SetTimerStep(double t) {TimerStep=t;}

bool bThread;

private:
CWorld *pWorld;
double TimerStep;
};

Body Emotion.cpp

#include "stdafx.h"
#include "Emotion.h"
#include

static void *thread_func(void *vptr_args)
{
CEmotion *pEm = (CEmotion*)vptr_args;

clock_t start;
double diff=0;
double step=0;

while(pEm->bThread)
{
start = clock();
pEm->Timer();
step=pEm->GetTimerStep()/1000.f;
diff = (double)(clock()-start)/CLOCKS_PER_SEC;

while (step>diff)
{
diff = (double)(clock()-start)/CLOCKS_PER_SEC;
}
}

pthread_exit((void *) 0);

return NULL;
};


CEmotion::CEmotion():TimerStep(5000)
{
bThread=false;
}

CEmotion::~CEmotion()
{
pWorld=NULL;
pthread_join( thread_timer, NULL);
}
void CEmotion::InitEmotion(CWorld *pW)
{
bThread=true;
pthread_create(&thread_timer, NULL, thread_func, this);
}

void CEmotion::Timer()
{
}

void CEmotion::StopTimer()
{
bThread=false;
}

댓글 없음:

댓글 쓰기