现在的位置: 首页 > 综合 > 正文

《ASCE1885的源码分析》の跨平台线程对象Thread封装基类

2013年08月07日 ⁄ 综合 ⁄ 共 1330字 ⁄ 字号 评论关闭

首先当然是先定义头文件Thread.h咯,如下:

#ifndef _THREAD_H

#define _THREAD_H

 

#ifdef _WIN32

#include <windows.h>

#else

#include <pthread.h>

#endif

 

#ifdef _WIN32

typedef unsigned threadfunc_t;

typedef void* threadparam_t;

#define STDPREFIX __stdcall

#else

typedef void* threadfunc_t;

typedef void* threadparam_t;

#define STDPREFIX

#endif

 

//线程的基类

class Thread

{

public:

    Thread(bool release=true);

    virtual ~Thread();

   

    static threadfunc_t STDPREFIX StartThread(threadparam_t);

   

    virtual void Run()=0;  //纯虚函数,由派生类实现

   

#ifdef _WIN32

    HANDLE GetThread(){return m_thread;}

    unsigned GetThreadId(){return m_dwThreadId;}

#else

    pthread_t GetThread(){return m_thread;}

#endif

 

    bool IsRunning();

    void SetRunning(bool x);

    bool IsReleased();

    void SetRelease(bool x);

    bool DeleteOnExit();

    void SetDeleteOnExit(bool x=true);

    bool IsDestructor();

   

protected:

#ifdef _WIN32

    HANDLE m_thread;

    unsigned m_dwThreadId;

#else

    pthread_t m_thread;

#endif

 

private:

    Thread(const Thread&){}

    Thread& operator=(const Thread&){return *this;}

    bool m_running;

    bool m_release;

    bool m_b_delete_on_exit;

    bool m_b_destructor;

};

 

#endif

 

接着是实现文件Thread.cpp,由于代码比较简单,就不多解释了,直接看代码里的注释就行了:

#include <stdio.h>

#ifdef _WIN32

#include <process.h>

#else

#include <unistd.h>

#endif

 

#include "Thread.h"

 

Thread::Thread(bool release)

    :m_thread(0),

    m_running(true),

    m_release(false),

    m_b_delete_on_exit(false),

    m_b_destructor(false)

抱歉!评论已关闭.