最近在写上位机,要用到QT,所以自己写的关于线程管理的类继承了QT里面的类。类内容如下:
class TinyThread : public QObject
{
Q_OBJECT
public:
TinyThread();
void runObj( TinyThreadFunc func, void* pData = 0, bool isAutoDelete = true);
void runObj( TinyThreadRunable* pRunable, bool isAutoDelete = true);
void runObj();
void suspend();
void resume();
void waitForClose( int waitTime = INFINITE);
bool isRunning() const;
void kill();
virtual ~TinyThread();
private:
virtual void run();
struct TinyThreadPrivate;
TinyThreadPrivate* pPrivateData;
};
首先看一下结构体TinyThreadPrivate里面包含哪些内容
struct TinyThread::TinyThreadPrivate
{
TinyThreadPrivate()
{
handle = 0;
func = 0;
//pRunable = 0;
isRunningNow = false;
isAutoDelete = true;
}
~TinyThreadPrivate()
{
}
void runIt()
{
if( func != 0)
{
(*func)(pFuncData ); //执行回调函数
}
else
{
pOwner -> run();
}
isRunningNow = false;
if( func && isAutoDelete )
delete pFuncData;
}
void init_run()
{
waitForClose();
if( handle == 0 )
{
unsigned int threadId;
handle = (HANDLE)_beginthreadex( 0, 0, TinyThreadCallBack, pOwner, CREATE_SUSPENDED, &threadId );
isRunningNow = true;
ResumeThread( handle);
}
}
void kill()
{
if (handle)
{
TerminateThread(handle, 0);
//_endthreadex(0);
CloseHandle(handle);
isRunningNow = false;
//return;
}
handle = 0;
}
void suspend()
{
if (handle)
SuspendThread(handle);
}
void resume()
{
if (handle)
ResumeThread(handle);
}
void waitForClose( int waitTime = INFINITE )
{
if( handle)
{
WaitForSingleObject( handle, waitTime );
CloseHandle( handle );
}
handle = 0;
}
bool isRunningNow; //线程是否在执行
TinyThreadFunc func; //函数指针
void *pFuncData; //数据指针,执行上面函数需要用到的参数
bool isAutoDelete; //是否自动删除上面的数据
HANDLE handle; //线程句柄
TinyThread* pOwner; //类指针
private:
static unsigned int __stdcall TinyThreadCallBack( LPVOID thisPtr )
{
TinyThread* pThis = static_cast< TinyThread* >(thisPtr);
pThis -> pPrivateData -> runIt();
return 0;
}
};
结构体包含的参数有,代码里有注释
结构体的构造函数初始化了4个参数变量,析构函数为空
void runIt()
如果函数指针不为0,则执行指针函数指向的函数;线程是否执行标志设置为false,并释放数据指针。
void suspend()
挂起线程
void resume()
恢复线程
void waitForClose( int waitTime = INFINITE )
等待线程执行完毕,释放线程句柄,将线程句柄置0.
void kill()
强制关闭线程,释放线程句柄,线程是否执行标志设置为false,线程句柄置0
void init_run()
等待上一个线程执行完毕(释放线程句柄,将线程句柄置0.),创建一个新的线程,线程被挂起,线程是否执行标志设置为true,恢复线程
static unsigned int __stdcall TinyThreadCallBack( LPVOID thisPtr )
然后看一下TinyThread类的构造函数
TinyThread::TinyThread()
{
pPrivateData = new TinyThreadPrivate;
pPrivateData -> pOwner = this;
}
为雷内结构体变量申请内存空间,并将类指针赋给结构体变量内的一个类指针变量