// 自己简单封装的thread类
// thread.h
#ifndef _THREAD_SPECIFICAL_H_
#define _THREAD_SPECIFICAL_H_
#include <Windows.h>
static UINT WINAPI threadFunc(LPVOID pParam);
class Thread
{
friend UINT WINAPI threadFunc(LPVOID pParam);
public:
Thread();
virtual ~Thread();
int start(void * = NULL);
// 调用wait()之后,主线程必须等待子线程结束之后才结束
void* wait();
// 停止线程
void stop();
// 分离线程:当子线程结束之后,系统自动清理线程所占用的资源,对于并发性很高的程序,一般都设置成分离线程
void detach();
static void sleep(UINT);
protected:
virtual void* run(void*) = 0;
private:
HANDLE threadHandle;
bool started;
bool detached;
void *param;
UINT threadID;
};
#endif
// thread.cpp
#include <process.h>
#include "thread.h"
UINT WINAPI threadFunc(LPVOID pParam)
{
Thread* thread = (Thread*)pParam;
return (UINT)thread->run(thread->param);
}
Thread::Thread()
{
started = false;
detached = false;
}
Thread::~Thread()
{
stop();
}
int Thread::start(void * pParam/* = NULL */)
{
if(!started)
{
param = pParam;
if(threadHandle = (HANDLE)_beginthreadex(NULL, 0, threadFunc, this, 0, &threadID))
{
if(detached)
CloseHandle(threadHandle);
started = true;
}
}
return started;
}
void* Thread::wait()
{
DWORD status = (DWORD)NULL;
if(started && !detached)
{
WaitForSingleObject(threadHandle, INFINITE);
GetExitCodeThread(threadHandle, &status);
CloseHandle(threadHandle);
detached = true;
}
return (void*)status;
}
void Thread::detach()
{
if(started && !detached)
CloseHandle(threadHandle);
detached = true;
}
void Thread::stop()
{
if(started && !detached)
{
TerminateThread(threadHandle, 0);
CloseHandle(threadHandle);
detached = true;
}
}
void Thread::sleep(UINT delay)
{
::Sleep(delay);
}
thread
最新推荐文章于 2023-08-21 11:13:15 发布