首页 > 代码库 > 转:一个跨WINDOWS LINUX平台的线程类
转:一个跨WINDOWS LINUX平台的线程类
来源: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 WINAPItypedef HANDLE DXHANDLE;#endif#ifdef DX_LINUX#include <pthread.h>#define DX_CALLBACKtypedef pthread_t DXHANDLE;#endifclass 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 = 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..\n"); return 0; }};int main(int argc, char* argv[]){ CTest a; a.Start(); //a.Detach(); //分离线程 if (false == a.Join()) { printf("join failed!\n"); } return 0;}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。