来源: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
#include "DXThread.h" CDXThread::CDXThread() { m_hThread = NULL; m_pParam = NULL; m_nRet = 0; m_bStart = false; m_nState = 0; } CDXThread::~CDXThread() { if (m_bStart && (m_nState == 0)) { Join(); } } int CDXThread::Run() { return 0; } bool CDXThread::Start() { if (true == m_bStart) return true; bool bOK = true; m_bStart = true; #ifdef DX_WINDOWS if (NULL == ( m_hThread = CreateThread(NULL, 0, (unsigned long(DX_CALLBACK*)(void*))&RunThread, this, 0, NULL) ) ) { bOK = false; } #endif #ifdef DX_LINUX if (0 != 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 == 1) return false; bool ret; m_bStart = false; #ifdef DX_WINDOWS while (1) { if (FALSE == GetExitCodeThread(m_hThread, &m_nRet)) { ret = false; break; } else { if (m_nRet == STILL_ACTIVE) { Sleep(100); continue; } CloseHandle(m_hThread); ret = true; break; } } #endif #ifdef DX_LINUX ret = (0 == pthread_join(m_hThread, (void **)&m_nRet)); #endif m_hThread = NULL; return ret; } bool CDXThread::Detach() { if (!m_bStart) return false; if (m_nState == 1) return false; m_nState = 1; #ifdef DX_WINDOWS return (TRUE == CloseHandle(m_hThread)); #endif #ifdef DX_LINUX return (0 == 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.. "); return 0; } }; int main(int argc, char* argv[]) { CTest a; a.Start(); //a.Detach(); //分离线程 if (false == a.Join()) { printf("join failed! "); } return 0; }