C++ 线程类的一个实现

.h

#ifndef CTHREAD_H_
#define CTHREAD_H_
#include "plat.h"

class CThread
{
public:
    enum
    {
        enmThreadTerminateTimeout = 2000,
    };
    CThread();
    virtual ~CThread();
    int32_t            Start();
    virtual int32_t    Terminate();
    virtual void    Execute();
protected:
#ifdef OS_WIN32
    uint32_t        m_nTimeOut;
    HANDLE            m_hThread;
#else
    pthread_t        m_thread;
    pthread_mutex_t m_stMutex;
#endif
    bool            m_bTerminated;
};

#endif

.cpp

#include "thread.h"
#include "common_api.h"
#ifdef   OS_WIN32
void ThreadProc(void *pParam)
{
    if (NULL == pParam)
    {
        return;
    }
    CThread *p = (CThread*)pParam;
    p->Execute();
}
#else
void* ThreadProc(void* pParam)
{
    if (NULL == pParam)
    {
        return NULL;
    }
    CThread *p = (CThread*)pParam;
    p->Execute();
    return NULL;
}
#endif

CThread::CThread()
{
#ifdef OS_WIN32
    m_nTimeOut = enmThreadTerminateTimeout;
    m_hThread = INVALID_HANDLE_VALUE;
#else
    m_thread = 0;
#endif
    m_bTerminated = false;
}

CThread::~CThread()
{
    Terminate();
}

int32_t CThread::Start()
{
    m_bTerminated = false;
#ifdef OS_WIN32
    m_hThread = (HANDLE)_beginthread(ThreadProc, 0, this);
#else
    pthread_create(&m_thread, NULL, ThreadProc, this);
#endif
    return 0;
}

int32_t CThread::Terminate()
{
    if (m_bTerminated == true)
    {
        return 0;
    }
    m_bTerminated = true;
#ifdef OS_WIN32
    if (m_hThread != INVALID_HANDLE_VALUE)
    {
        // wait for (m_nTimeOut) milliseconds or Excute() return
        WaitForSingleObject(m_hThread, m_nTimeOut);
    }
#else
    if (m_thread != 0)
    {
        // wait Excute() return
        pthread_join(m_thread, NULL);
    }
#endif
    return 0;
}

void CThread::Execute()
{
    uint32_t n = 0;
    while (!m_bTerminated)
    {
        if ((++n) % 1000 == 0)
        {
            printf("%d\n", n);
        }
        Delay(1);
    }
#ifdef WIN32
    _endthread();
#else
    pthread_exit(NULL);
#endif
}

 

posted @ 2016-07-29 20:14  你好阿汤哥  Views(1210)  Comments(0Edit  收藏  举报