C++ thread 线程封装类

C++ thread 线程封装类

    • Thread.h
    • Thread.cpp
    • 使用WThread

      思路是这样的,写一个Thread抽象类,有函数virtual void Run()=0,类中调用Window API函数CreateThread()创建并启动线程,所有线程都执行同一个静态函数ThreadFunction(LPVOID Param),param传递线程对象的this指针

CreateThread(NULL, 0, Thread::WThreadFunctionLinek, (LPVOID)this, 0, &nthreadID);

      在ThreadFunction函数中将Param强转为Thread类型,利用多态特性调用Run()函数,Run的具体实现由子类完成。

DWORD __stdcall Thread::WThreadFunctionLinek(LPVOID Param)
{
      ThreadpThread = ((Thread)Param);
      pThread->Run();
      pThread->Stop();
      return 0;
}

Thread.h

#pragma once
#include 

class Thread;
typedef void (*WThreadFunction)(Thread* pobj);

//线程类;
class Thread
{
private:
	HANDLE hThread;			//线程句柄;
	DWORD nthreadID;		//线程ID;
	static DWORD __stdcall WThreadFunctionLinek(IN LPVOID Param); //静态方法
protected:
	bool bRun;
	virtual void Run() = 0;			//继承并重写;
public:
	Thread();
	void Start();		//运行;
	void Stop();		//停止;
	void WaitExit();	//等待线程退出;
};

Thread.cpp

#include "Thread.h"

Thread::Thread()
{
	bRun = false;
}
void Thread::Start()
{
	if(bRun == true)
		return;
	bRun = true;
	hThread = CreateThread(NULL, 0, Thread::WThreadFunctionLinek, (LPVOID)this, 0, &nthreadID);
	if(hThread == NULL)
	{
		return;
	}
}
void Thread::Stop()
{
	if(bRun == false)
		return;
	bRun = false;
	TerminateThread(hThread,EXIT_FAILURE);
	CloseHandle(hThread);
	hThread = NULL;
}

void Thread::WaitExit()
{
	if(bRun == false)
		return;
	if(hThread == NULL)
		return;
	WaitForSingleObject(hThread, INFINITE);
}

DWORD __stdcall Thread::WThreadFunctionLinek(LPVOID Param)
{
	Thread* pThread = ((Thread*)Param);
	pThread->Run();
	pThread->Stop();
	return 0;
}

使用WThread


//继承WThread;
class Example: public WThread
{
public:
	//重写Run;
	void Run()
	{
		while(this->bRun)
		{
			printf("Hello thread\n");
			Sleep(1000);
		}
	}
};

Wint32 _tmain(Wint32 argc, _TCHAR* argv[])
{
	//实例化;
	Example e;
	//启动线程;
	e.Start();

	getchar();
	return 0;
}

你可能感兴趣的:(后台,C++)