Here's what I'm trying to do. I want a base class name CThreadKernel, which allows me to encapsulate (and ultimately forget about) the creation of a thread. The base class creates the thread and destroys it. This is an abstract class. Not implemented in the base class are OnInitialize(), OnExecute() and OnUninitialize(). I plan to extend this class for each of my threads. So here's the code... (Keep in mind, a lot of this is bad test code)
threadkernel.h
#ifndef __THREADKERNEL_INCLUDED__#define __THREADKERNEL_INCLUDED__#include "system.h"#include <process.h>#define THREADKERNEL_RET_OKAY 0#define THREADKERNEL_RET_ERROR -1class CThreadKernel {public: CThreadKernel (); ~CThreadKernel (); void SetDelay (int milliseconds); BOOL Execute (); void Kill (); int GetDelay (); BOOL IsActive (); void Thread ();protected: virtual BOOL OnInitialize () = 0; virtual BOOL OnExecute () = 0; virtual BOOL OnUninitialize () = 0;private: volatile BOOL active; int delay;};#endif
threadkernel.cpp
#include "threadkernel.h"CThreadKernel *temp = NULL;void Launch ();void ThreadProc (void *param);void Launch () { _beginthread (ThreadProc, 0, NULL);}void ThreadProc (void *param) { temp->Thread();}CThreadKernel::CThreadKernel () { this->active = false; this->delay = 0;}CThreadKernel::~CThreadKernel () { if (this->active) { this->Kill (); Sleep (500); }}void CThreadKernel::SetDelay (int milliseconds) { this->delay = milliseconds;}BOOL CThreadKernel::Execute () { if (!this->active) { this->active = true; if (this->OnInitialize ()) return THREADKERNEL_RET_ERROR; temp = this; Launch (); } else { return THREADKERNEL_RET_ERROR; } return THREADKERNEL_RET_OKAY;}void CThreadKernel::Kill () { this->active = false;}int CThreadKernel::GetDelay () { return this->delay;}BOOL CThreadKernel::IsActive () { return this->active;}void CThreadKernel::Thread () { do { if (this->OnExecute ()) this->active = false; if (this->delay > 0) Sleep (this->delay); } while (this->active); this->OnUninitialize (); _endthread ();}
I would like to think that I don't need the temp, ThreadProc and Launch variables/functions. But, like I said, this is all in testing. I've seen examples of this work in straight "C" but this is being very quirky.
This code, when used with multiple threads, only allows one thread to work. Creating a single thread works beautifully. Once you add another thread, the previous thread craps out.
[edit]
BTW, I should also mention that this is a purely OO Win32 app. Have I outgrown _beginthread?