Here is my C++ Win32 thread wrapper.
I put it into the public domain 😉
If you find any flaws, don’t hesitate to contact me, or just put a comment.
I think this code is straightforward and self-explainable.

class Thread {
public:
enum Priority {
LOWEST = THREAD_PRIORITY_LOWEST,
LOW = THREAD_PRIORITY_BELOW_NORMAL,
NORMAL = THREAD_PRIORITY_NORMAL,
HIGH = THREAD_PRIORITY_ABOVE_NORMAL,
HIGHEST = THREAD_PRIORITY_HIGHEST
};

public:
Thread()
: _handle (NULL)
{
}

virtual ~Thread() {
Kill();
}

bool Start(bool suspended = false) {
_running = true;
_suspended = suspended;

DWORD flags = suspended ? CREATE_SUSPENDED : 0;
if (_handle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)_ThreadFunc, this, flags, &_id)) {
return true;
} else {
_suspended = false;
_running = false;
return false;
}
}

bool Stop(DWORD timeout, bool force = false) {
_running = false;
if (force) {
if (WaitForSingleObject(_handle, timeout) == WAIT_OBJECT_0) {
return true;
} else {
BOOL result = TerminateThread(_handle, 1);
CloseHandle(_handle);
_handle = NULL;
_running = false;
_suspended = false;
return result == TRUE;
}
} else {
return WaitForSingleObject(_handle, timeout) == WAIT_OBJECT_0;
}
}

bool Kill() {
BOOL result = FALSE;
if (_handle) {
result = TerminateThread(_handle, 1);
CloseHandle(_handle);
_handle = NULL;
}
_suspended = false;

return result == TRUE;
}

bool Suspend() {
_suspended = true;
return SuspendThread(_handle) != -1;
}

bool Resume() {
_suspended = false;
return ResumeThread(_handle) != -1;
}

bool Wait(DWORD timeout = INFINITE) {
return WaitForSingleObject(_handle, timeout) == WAIT_OBJECT_0;
}

bool SetPriority(Priority priority) {
return SetThreadPriority(_handle, (DWORD)priority) == TRUE;
}

bool SetIdealProcessor(int index) {
return SetThreadIdealProcessor(_handle, index) != -1;
}

bool ClearCpuAffinity() {
}

bool AddCpuAffinity() {
}

bool IsSuspended() const {
return _suspended;
}

bool IsRunning() const {
return _running;
}

unsigned GetID() const {
return _id;
}

private:
static DWORD WINAPI _ThreadFunc(LPVOID pvThread) {
if (Thread* pThis = (Thread*)pvThread) {
pThis->Run();
pThis->_running = false;
pThis->_suspended = false;
}
return 0;
}

protected:
virtual void Run() = 0;

private:
HANDLE _handle;
DWORD _id;
bool _suspended;
volatile bool _running;
};

Advertisements