#include "thread.h"

int rThread::numThreads;

void WINAPI rThreadProc(rThread *pThis)
{
	return pThis->rThreadLoop();
}

rThread::rThread()
{
	numThreads = 0;
	timeToEnd = 1;
} 
rThread::~rThread()
{
	rKillThread();
}

bool rThread::rCreateThread(bool startImmediately)
{ 
	threadHandle = CreateThread(NULL, 
								0, 
								(LPTHREAD_START_ROUTINE)rThreadProc, 
								this, 
								(startImmediately) ? 0 : CREATE_SUSPENDED, 
								0);
	bThreadRunning = startImmediately;
	numThreads++;
	active = true;
	return (threadHandle != 0);
}

void rThread::rSuspendThread()
{
	SuspendThread(threadHandle);
	bThreadRunning = false;
}

int rThread::rResumeThread()
{
	bThreadRunning = true;
	return (int)ResumeThread(threadHandle);
}

void rThread::rKillThread()
{
	active = false;
	rResumeThread();
	WaitForSingleObject(threadHandle, timeToEnd);
	CloseHandle(threadHandle);
	numThreads--;
}


int rThread::getNumThreads()
{
	return numThreads;
}

	