#include
class Thread{
private:
class ThreadContext{
public:
HANDLE handle;
DWORD threadId;
LPVOID userData;
DWORD exitCode;
public:
ThreadContext(){
/*konstruktor*/
/*mengalokasikan tempat di memori*/
memset(this, 0, sizeof(this));
}
};
protected:
ThreadContext threadContext;
LPTHREAD_START_ROUTINE worker;
public:
Thread(){
/*konstruktor*/
/*mendaftarkan thread yang dialokasikan*/
worker = Thread::EntryPoint;
}
Thread(LPTHREAD_START_ROUTINE lpExternalRoutine){
/*konstruktor*/
/*meregistrasi thread yang dialokasikan*/
Attach(lpExternalRoutine);
}
~Thread(){
/*destruktor*/
if ( threadContext.handle ){
/*jika thread masih berjalan maka dihentikan*/
Stop(true);
}
}
DWORD Start( void* arg = NULL ){
/*menjalankan thread*/
threadContext.userData = arg;
threadContext.handle = CreateThread(NULL, 0, worker, this, 0, &threadContext.threadId);
threadContext.exitCode = (DWORD)-1;
return GetLastError();
}
DWORD Stop ( bool forceKill = false ){
/*menghentikan jalannya thread*/
if ( threadContext.handle ){
GetExitCodeThread(threadContext.handle, &threadContext.exitCode);
if ( threadContext.exitCode == STILL_ACTIVE && forceKill ){
TerminateThread(threadContext.handle, DWORD(-1));
}
threadContext.handle = NULL;
}
return threadContext.exitCode;
}
DWORD GetExitCode() const {
/*mengembalikan nilai kode keluar thread*/
if ( threadContext.handle ){
/*jika thread masih berjalan, ambil kode keluarnya*/
GetExitCodeThread(
threadContext.handle, (LPDWORD)&threadContext.exitCode);
}
return threadContext.exitCode;
}
void Attach( LPTHREAD_START_ROUTINE lpThreadFunc ){
/*meregistrasi thread*/
worker = lpThreadFunc;
}
void Detach( void ){
worker = Thread::EntryPoint;
}
protected:
static DWORD WINAPI EntryPoint( LPVOID arg){
Thread *parent = reinterpret_cast
parent->Run( parent->
threadContext.userData );
return STILL_ACTIVE;
}
virtual DWORD Run( LPVOID ){
return threadContext.exitCode;
}
};
class LastThread : public Thread{
public:
LastThread(){
/*konstruktor*/
}
virtual DWORD Run( LPVOID){
int i;
for(i=0;i<=10;){
printf("proses LastThread\n");
Sleep(1000);
}
}
};
class NewThread : public Thread{
public:
NewThread(){
/*konstruktor*/
}
virtual DWORD Run( LPVOID){
int i;
for(i=0;i<=10;){
printf("proses NewThread\n");
Sleep(1000);
}
}
};
int main( void ){
LastThread lt;
NewThread nt;
lt.Start(NULL);
nt.Start(NULL);
SleepEx(11 * 1000, FALSE);
lt.Stop(true);
nt.Stop(true);
return 0;
}