Creating classes in C, and still be able to run seperat thread per instance example.
HEADER file
#pragma once class Web { public: Web(); ~Web(void); DWORD Init(); int Process(); static int runProcess (void* pThis); private: HANDLE hThread; // Class thread HANDLE EventList[2]; }
C file
Web::Web() { hThread = NULL; EventList[0] = NULL; EventList[1] = NULL; } Web::~Web(void) { DWORD ExitCode; // First Check if our thread is running... GetExitCodeThread(hThread,&ExitCode); if (ExitCode != 259) { printf("Thread allready dead\r\n"); CloseHandle(hThread); hThread = NULL; } if (hThread != NULL) { if (EventList[0] != NULL) { // Tell to shutdown... SetEvent(EventList[0]); ExitCode =259; DWORD MaxWait = 20; // Max Wait loops (0.5 sec) to wait before killing thread... while (ExitCode == 259 && MaxWait >0) { if (GetExitCodeThread(hThread,&ExitCode) ==0) { ErrorCode = GetLastError(); printf ("Failed to get Exitcode of Web-Executer\r\n"); } Sleep(100); MaxWait--; } if (ExitCode == 259) { printf("Web-Executer did not respond to Shutdown signal, killing the hard way!\r\n"); if (TerminateThread(hThread,1) ==0) { ErrorCode = GetLastError(); printf("Failed to kill Web-Executer.. DOH!!! Abandon all hope!\r\n"); } } printf ("Web-Executer died nicely."); } if (hThread != NULL) { CloseHandle(hThread); hThread = NULL; } } if (EventList[0] != NULL) { CloseHandle(EventList[0]); // Quit Event EventList[0] = NULL; } if (EventList[1] != NULL) { CloseHandle(EventList[1]); // WakeUpEvent EventList[1] = NULL; } } DWORD Web::Init() { // Create ShutDown Event EventList[0] = CreateEvent(NULL,TRUE,FALSE,NULL); if (EventList[0] == NULL) { ErrorCode = GetLastError(); printf("Unable to create Event0\r\n"); return -12; } // Create WakeUp Event EventList[1] = CreateEvent(NULL,TRUE,FALSE,NULL); if (EventList[1] == NULL) { ErrorCode = GetLastError(); printf("Unable to create Event1\r\n"); return -12; } printf("Now starting Web Thread\r\n"); hThread = CreateThread (NULL, 0, (unsigned long (__stdcall *)(void *))this->runProcess, (void *)this, 0, NULL); return 0; } // CallBack workaround for internal thread. int Web::runProcess (void* pThis) { return ((Web*)(pThis))->Process(); } // True thread starts here int Web::Process () { SetThreadPriority(GetCurrentThread,THREAD_PRIORITY_BELOW_NORMAL); printf("Thread is alive\r\n"); while (1) { DWORD WaitRes = WaitForMultipleObjects(2,EventList,FALSE,INFINITE); printf("Web-Executer wakeup\r\n"); if (WaitRes == WAIT_OBJECT_0) { printf("Web-Executer(%d) got shutdown event...\r\n",GetCurrentThreadId()); // Got ShutDownEvent; ExitThread(0); } else if (WaitRes == WAIT_OBJECT_0 +1) { printf("JOB signaled\r\n"); ResetEvent(EventList[1]); } } // Should never be here... printf("Thread(%d) is executing something I would never do!!!\r\n",GetCurrentThreadId()); ExitThread(0); return 0; }