51 lines
1021 B
C++
51 lines
1021 B
C++
|
|
#include "thread.h"
|
|||
|
|
#include <Windows.h>
|
|||
|
|
#include <assert.h>
|
|||
|
|
#include <process.h>
|
|||
|
|
|
|||
|
|
//volatile unsigned int Thread::numCreated_ = 0;
|
|||
|
|
volatile LONG Thread::numCreated_ = 0;
|
|||
|
|
Thread::Thread(void* pthis,const ThreadFunc& func, const std::string& name)
|
|||
|
|
: pThis_(pthis), started_(false), threadId_(0), func_(func), name_(name)
|
|||
|
|
{
|
|||
|
|
InterlockedIncrement(&numCreated_);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
Thread::~Thread()
|
|||
|
|
{
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
void Thread::start()
|
|||
|
|
{
|
|||
|
|
assert(!started_);
|
|||
|
|
started_ = true;
|
|||
|
|
threadId_ = _beginthreadex(NULL, 0, startThread, this, 0, NULL);
|
|||
|
|
if (0 == threadId_)
|
|||
|
|
{
|
|||
|
|
// OutputDebugString(L"create thread fail");
|
|||
|
|
}
|
|||
|
|
else
|
|||
|
|
{
|
|||
|
|
// OutputDebugString(L"create thread success");
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
void Thread::join()
|
|||
|
|
{
|
|||
|
|
assert(started_);
|
|||
|
|
started_ = false;
|
|||
|
|
WaitForSingleObject((HANDLE)threadId_, INFINITE);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
unsigned int Thread::startThread(void *obj)
|
|||
|
|
{
|
|||
|
|
Thread *thread = static_cast<Thread*>(obj);
|
|||
|
|
thread->runInThread();
|
|||
|
|
return 0;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
void Thread::runInThread()
|
|||
|
|
{
|
|||
|
|
if (func_) { func_(pThis_); }
|
|||
|
|
}
|