来源:http://blog.csdn.net/dengxu11/article/details/7232681
继Windows下实现一个CThread封装类之后,这里我再实现一个跨WINDOWS LINUX平台的线程类
头文件 DXThread.h
#ifndef __DXTHREAD_H__
#define __DXTHREAD_H__ #define DX_WINDOWS //在WINDOWS上就打开它
//#define DX_LINUX //在LINUX 上就打开它 #ifdef DX_WINDOWS
#include <windows.h>
#define DX_CALLBACK WINAPI
typedef HANDLE DXHANDLE;
#endif #ifdef DX_LINUX
#include <pthread.h>
#define DX_CALLBACK
typedef pthread_t DXHANDLE;
#endif class CDXThread
{
public:
CDXThread();
virtual ~CDXThread();
virtual int Run();
bool Start();
bool Join();
bool Detach(); private:
static void* DX_CALLBACK RunThread(void* pParam);
DXHANDLE m_hThread;
void* m_pParam;
unsigned long m_nRet;
protected:
bool m_bStart;
int m_nState;
}; #endif //DXThread.h
//源文件 DXThread.cpp
#include "DXThread.h" CDXThread::CDXThread()
{
m_hThread = NULL;
m_pParam = NULL;
m_nRet = ;
m_bStart = false;
m_nState = ;
} CDXThread::~CDXThread()
{
if (m_bStart && (m_nState == ))
{
Join();
}
} int CDXThread::Run()
{
return ;
} bool CDXThread::Start()
{
if (true == m_bStart)
return true; bool bOK = true;
m_bStart = true;
#ifdef DX_WINDOWS
if (NULL ==
(
m_hThread = CreateThread(NULL, ,
(unsigned long(DX_CALLBACK*)(void*))&RunThread, this, , NULL)
)
)
{
bOK = false;
}
#endif #ifdef DX_LINUX
if ( != pthread_create(&m_hThread, NULL, RunThread, this))
{
bOK = false;
}
#endif if (!bOK)
{
m_bStart = false;
return false;
} return true;
} bool CDXThread::Join()
{
if (!m_bStart)
return false; if (m_nState == )
return false; bool ret;
m_bStart = false; #ifdef DX_WINDOWS while ()
{
if (FALSE == GetExitCodeThread(m_hThread, &m_nRet))
{
ret = false;
break;
}
else
{
if (m_nRet == STILL_ACTIVE)
{
Sleep();
continue;
}
CloseHandle(m_hThread);
ret = true;
break;
}
} #endif #ifdef DX_LINUX
ret = ( == pthread_join(m_hThread, (void **)&m_nRet));
#endif m_hThread = NULL;
return ret;
} bool CDXThread::Detach()
{
if (!m_bStart)
return false; if (m_nState == )
return false; m_nState = ;
#ifdef DX_WINDOWS
return (TRUE == CloseHandle(m_hThread));
#endif #ifdef DX_LINUX
return ( == pthread_detach(m_hThread));
#endif } void* DX_CALLBACK CDXThread::RunThread(void* pParam)
{
CDXThread* pThis = (CDXThread*)pParam;
int nRet = pThis->Run();
return (void *)nRet;
}
//调用实例
#include <stdio.h>
#include "DXThread.h" class CTest : public CDXThread
{
public:
int Run()
{
printf("1..\n");
return ;
}
}; int main(int argc, char* argv[])
{
CTest a;
a.Start(); //a.Detach(); //分离线程 if (false == a.Join())
{
printf("join failed!\n");
} return ;
}