windows下创建自己的线程方式有几种。MFC的AfxBeginThread(),win32的CreateThread(但是不推荐,原因可以参考MSDN及《windows核心编程》)。还可以用运行库的_beginthreadex。总之,创建线程的语句也还并不很复杂。
如果每次创建线程都要把那条语句写一遍,那也太笨拙了。同时,如果是在类里用的话,线程函数要定义成静态函数。作为一个懒人,理所应当避免写重复的代码,于是一个自己的线程类就有必要了。
//Thread.h
#ifndef LIB_THREAD_CLASS_H
#define LIB_THREAD_CLASS_H
#pragma once
#include "ThreadMutex.h"
class CThread
{
public:
CThread(void);
virtual ~CThread(void);
virtual bool Start(void);
virtual void Cancel(void);
virtual void Run(void) = 0;
virtual bool IsRunning(void);
virtual bool SetPriority(int nPriority);
virtual DWORD Resume(void);
protected:
CThread(const CThread &);
CThread & operator = (const CThread &);
static unsigned _stdcall ThreadFunc(void *pArg);
void *m_hThread;
unsigned int m_hThreadID;
bool m_bCancel; //用于在Run()函数里进行判断
CThreadMutexObject m_mutexThreadCtl;
};
#endif
//Thread.cpp
#include "Thread.h"
#include <process.h>
#include <windows.h>
#define WAIT_TIME 1000
CThread::CThread(void):m_hThread(NULL),m_hThreadID(0),m_bCancel(false)
{}
CThread::~CThread(void)
{}
bool CThread::Start(void)
{
CThreadMutex lock(m_mutexThreadCtl);
if (NULL != m_hThread)
{
DWORD dwExitCode = 0;
if (::GetExitCodeThread(m_hThread, &dwExitCode) == TRUE)
{
if (STILL_ACTIVE == dwExitCode)
{
return false;
}
}
else
return false;
}
m_bCancel = false;
m_hThread = (void*)_beginthreadex(NULL,0,&CThread::ThreadFunc,this,0,&m_hThreadID);
return true;
}
void CThread::Cancel(void)
{
if (NULL == m_hThread)
return ;
CThreadMutex lock(m_mutexThreadCtl);
m_bCancel = true;
DWORD dw = ::WaitForSingleObject(m_hThread,WAIT_TIME);
switch (dw)
{
case WAIT_TIMEOUT:
::TerminateThread(m_hThread,1);
break;
default:
;
}
::CloseHandle(m_hThread);
m_hThread = NULL;
m_hThreadID = 0;
}
unsigned __stdcall CThread::ThreadFunc(void * pArg)
{
CThread * pThis = (CThread*)pArg;
pThis->Run();
_endthreadex(0);
return 0;
}
bool CThread::IsRunning(void)
{
if (NULL == m_hThread)
return false;
DWORD dwExitCode = 0;
::GetExitCodeThread(m_hThread, &dwExitCode);
if (STILL_ACTIVE == dwExitCode)
return true;
return false;
}
bool CThread::SetPriority(int nPriority)
{
if (NULL == m_hThread)
return false;
BOOL b = ::SetThreadPriority(m_hThread,nPriority);
if (FALSE == b)
return false;
return true;
}
DWORD CThread::Resume(void)
{
return ::ResumeThread(m_hThread);
}
使用嘛,很简单。定义一个继承自CThread的类,实现它的Run()函数就好了。运行的话执行它的Start()函数就好了。注意,不是执行Run(),如果执行Run()的话也能运行,但是在当前线程里运行,而不是新启动一个线程运行。
写完了,再看看,和JAVA里的线程类很相似啊。英雄所见略同啊;-)