关于Linux 系统下 C++ 的多线程基类 Thread

最近在Linux 下用C++做的东西,原来是使用“多进程”方式实现,现在随着工程的增大,“多进程”的“变量共享”问题已经十分突出了,虽然可以使“内存共享”等方式实现,但大量的“内存共享”会导致代码混乱。。
所以决心将整个工程重新写,使用“多线程”方式实现,这样可以大大较少“内存共享”的使用次数。

下面是我写的基类,把代码保存在名为 Thread.h 的头文件中。
====================================传说中的分割线=================================
/* 
 * File:   Thread.h
 * Author: Null
 * Blog: http://hi.baidu.com/hetaoos
 * Created on 2008年7月30日, 上午10:13
 */

/*
 * 在编译的时候记得加上参数:-lpthread
 * 
 */

#ifndef _THREAD_H
#define _THREAD_H


#include <pthread.h>
#include <unistd.h>

class Thread
{
private:
    //当前线程的线程ID
    pthread_t tid;
    //线程的状态
    int threadStatus;
    //获取执行方法的指针
    static void* run0(void* pVoid);
    //内部执行方法
    void* run1();
public:
    //线程的状态-新建
    static const int THREAD_STATUS_NEW = 0;
    //线程的状态-正在运行
    static const int THREAD_STATUS_RUNNING = 1;
    //线程的状态-运行结束
    static const int THREAD_STATUS_EXIT = -1;
    //构造函数
    Thread();
    //线程的运行实体
    virtual void run() = 0;
    //开始执行线程
    bool start();
    //获取线程ID
    pthread_t getThreadID();
    //获取线程状态
    int getState();
    //等待线程直至退出
    void join();
    //等待线程退出或者超时
    void join(unsigned long millisTime);
};

void* Thread::run0(void* pVoid)
{
    Thread* p = (Thread*) pVoid;
    p->run1();
    return p;
}

void* Thread::run1()
{

    threadStatus = THREAD_STATUS_RUNNING;
    tid = pthread_self();
    run();
    threadStatus = THREAD_STATUS_EXIT;
    tid = 0;
    pthread_exit(NULL);
}

Thread::Thread()
{
    tid = 0;
    threadStatus = THREAD_STATUS_NEW;
}

bool Thread::start()
{
    return pthread_create(&tid, NULL, run0, this) == 0;
}

pthread_t Thread::getThreadID()
{
    return tid;
}

int Thread::getState()
{
    return threadStatus;
}

void Thread::join()
{
    if (tid > 0)
    {
        pthread_join(tid, NULL);
    }
}

void Thread::join(unsigned long millisTime)
{

    if (tid == 0)
    {
        return;
    }
    if (millisTime == 0)
    {
        join();
    }else
    {
        unsigned long k = 0;
        while (threadStatus != THREAD_STATUS_EXIT && k <= millisTime)
        {
            usleep(100);
            k++;
        }
    }
}
#endif /* _THREAD_H */

====================================传说中的分割线=================================
用法简单类似于 Java 的 Thread,继承 Thread 类,然后重写 void run() 方法,然后用 bool start () 方法开始运行。这样完全屏蔽掉了线程的具体操作。使用简单方便。

具体看下面的示例代码。
====================================传说中的分割线=================================
/*
 * File:   newmain.cc
 * Author: Null
 * Blog: http://hi.baidu.com/hetaoos
 * Created on 2008年7月30日, 上午11:49
 */


#include "Thread.h"
#include <iostream.h>

class MultiThread : public Thread
{
public:

    void run()
    {
        int number = 0;
        for (int i = 0; i < 10; i++)
        {
            cout << "Current number is " << number++;
            cout << " PID is " << getpid() << " TID is " << getThreadID() << endl;
            sleep(1);
        }
    }
};


int main(int argc, char** argv)
{
    bool ret;
    MultiThread *mt;
    mt = new MultiThread();
    ret = mt->start();
    mt->join(6000);
    return (EXIT_SUCCESS);
}
====================================传说中的分割线=================================
上面的代码,由于 join 设置超时为 6 秒,所以没能完全打印出10条记录就已经退出了。

上面的代码还有些不足:
1,���有线程属性的设置,这个当初也考虑过,但是有些麻烦,也很少用。如果哪位大侠实现了比较完成的 Thread 类,麻烦发个给我。

2,线程的控制有待完善,这个阿,暂时没有时间研究。linux


在原来的基础上,进行了加强,使之进一步接近 Java 中 Thread 和 Runnable 的用法。

下面是我写的基类,把代码保存在名为 Thread.h 的头文件中。
====================================传说中的分割线=================================

/* 
 * File:   Thread.h
 * Author: Null
 * Blog: http://hi.baidu.com/hetaoos
 * Created on 2008年7月30日, 上午10:13
 */

/*
 * 在编译的时候记得加上参数:-lpthread
 * 
 */

#ifndef _THREAD_H
#define _THREAD_H


#include <pthread.h>
#include <unistd.h>

/*
 * 线程运行实体类
 */
class Runnable
{
public:
    //运行实体
    virtual void run() = 0;
};

/*
 * 线程类
 *
 */
class Thread : public Runnable
{
private:
    //线程初始化序号
    static int threadInitNumber;
    //当前线程初始化序号
    int curThreadInitNumber;
    //线程体
    Runnable *target;
    //当前线程的线程ID
    pthread_t tid;
    //线程的状态
    int threadStatus;
    //线程属性
    pthread_attr_t attr;
    //线程优先级
    sched_param param;
    //获取执行方法的指针
    static void* run0(void* pVoid);
    //内部执行方法
    void* run1();
    //获取一个线程序号
    static int getNextThreadNum();

public:
    //线程的状态-新建
    static const int THREAD_STATUS_NEW = 0;
    //线程的状态-正在运行
    static const int THREAD_STATUS_RUNNING = 1;
    //线程的状态-运行结束
    static const int THREAD_STATUS_EXIT = -1;
    //构造函数
    Thread();
    //构造函数
    Thread(Runnable *iTarget);
    //析构
    ~Thread();
    //线程的运行实体
    void run();
    //开始执行线程
    bool start();
    //获取线程状态
    int getState();
    //等待线程直至退出
    void join();
    //等待线程退出或者超时
    void join(unsigned long millisTime);
    //比较两个线程时候相同,通过 curThreadInitNumber 判断
    bool operator ==(const Thread *otherThread);
    //获取This线程ID
    pthread_t getThreadID();
    //获取当前线程ID
    static pthread_t getCurrentThreadID();
    //当前线程是否和某个线程相等,通过 tid 判断
    static bool isEquals(Thread *iTarget);
    //设置线程的类型:绑定/非绑定
    void setThreadScope(bool isSystem);
    //获取线程的类型:绑定/非绑定
    bool getThreadScope();
    //设置线程的优先级,1-99,其中99为实时;意外的为普通
    void setThreadPriority(int priority);
    //获取线程的优先级
    int getThreadPriority();
};

int Thread::threadInitNumber = 1;

inline int Thread::getNextThreadNum()
{
    return threadInitNumber++;
}

void* Thread::run0(void* pVoid)
{
    Thread* p = (Thread*) pVoid;
    p->run1();
    return p;
}

void* Thread::run1()
{

    threadStatus = THREAD_STATUS_RUNNING;
    tid = pthread_self();
    run();
    threadStatus = THREAD_STATUS_EXIT;
    tid = 0;
    pthread_exit(NULL);
}

void Thread::run()
{
    if (target != NULL)
    {
        (*target).run();
    }
}

Thread::Thread()
{
    tid = 0;
    threadStatus = THREAD_STATUS_NEW;
    curThreadInitNumber = getNextThreadNum();
    pthread_attr_init(&attr);
}

Thread::Thread(Runnable *iTarget)
{
    target = iTarget;
    tid = 0;
    threadStatus = THREAD_STATUS_NEW;
    curThreadInitNumber = getNextThreadNum();
    pthread_attr_init(&attr);
}

Thread::~Thread()
{
    pthread_attr_destroy(&attr);
}

bool Thread::start()
{
    return pthread_create(&tid, &attr, run0, this) == 0;
}

inline pthread_t Thread::getCurrentThreadID()
{
    return pthread_self();
}

inline pthread_t Thread::getThreadID()
{
    return tid;
}

inline int Thread::getState()
{
    return threadStatus;
}

void Thread::join()
{
    if (tid > 0)
    {
        pthread_join(tid, NULL);
    }
}

void Thread::join(unsigned long millisTime)
{

    if (tid == 0)
    {
        return;
    }
    if (millisTime == 0)
    {
        join();
    }else
    {
        unsigned long k = 0;
        while (threadStatus != THREAD_STATUS_EXIT && k <= millisTime)
        {
            usleep(100);
            k++;
        }
    }
}

bool Thread::operator ==(const Thread *otherThread)
{
    if (otherThread == NULL)
    {
        return false;
    }
    if (curThreadInitNumber == (*otherThread).curThreadInitNumber)
    {
        return true;
    }
    return false;
}

bool Thread::isEquals(Thread *iTarget)
{
    if (iTarget == NULL)
    {
        return false;
    }
    return pthread_self() == iTarget->tid;
}

void Thread::setThreadScope(bool isSystem)
{
    if (isSystem)
    {
        pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
    }else
    {
        pthread_attr_setscope(&attr, PTHREAD_SCOPE_PROCESS);
    }
}

bool Thread::getThreadScope()
{
    int scopeType = 0;
    pthread_attr_getscope(&attr, &scopeType);
    return scopeType == PTHREAD_SCOPE_SYSTEM;
}

void Thread::setThreadPriority(int priority)
{
    pthread_attr_getschedparam(&attr, &param);
    param.__sched_priority = priority;
    pthread_attr_setschedparam(&attr, &param);
}

int Thread::getThreadPriority()
{
    pthread_attr_getschedparam(&attr, &param);
    return param.__sched_priority;
}
#endif /* _THREAD_H */
====================================传说中的分割线=================================


具体看下面的示例代码。
呵呵,用法和 Java 的 Thread 很相似吧。
下面一共生成了3个线程,3个线程都共享 MultiThread::run()
在 run() 里面通过判断线程的实体来分离各个线程的工作。

====================================传说中的分割线=================================
/* 
 * File:   newmain.cc
 * Author: Null
 * Blog: http://hi.baidu.com/hetaoos
 * Created on 2008年7月30日, 上午12:49
 */


#include "Thread.h"
#include <iostream.h>

class MultiThread : public Thread
{
public:

    Thread *th1;
    Thread *th2;

    void Test()
    {
        th1 = new Thread(this);
        th1->setThreadPriority(99);
        th2 = new Thread(this);
        start();
        th1->start();
        th2->start();
        th1->join();
        th2->join();
    }

    void run()
    {
        //Thread->isEquals(th1)
        if (Thread::isEquals(th1))
        {
            int number = 100;
            for (int i = 0; i < 10; i++)
            {
                cout << "this is thread1 number is " << number++;
                cout << " \tpid is " << getpid() << " tid is " << getCurrentThreadID() << "  Priority:" << th1->getThreadPriority() << endl;
                sleep(1);
            }
        }else if (Thread::isEquals(th2))
        {
            int number = 200;
            for (int i = 0; i < 10; i++)
            {
                cout << "this is thread2 number is " << number++;
                cout << " \tpid is " << getpid() << " tid is " << getCurrentThreadID() << "  Priority:" << th2->getThreadPriority() << endl;
                sleep(1);
            }
        }else if (Thread::isEquals(this))
        {
            int number = 300;
            for (int i = 0; i < 10; i++)
            {
                cout << "this is thread0 number is " << number++;
                cout << " \tpid is " << getpid() << " tid is " << getCurrentThreadID() << "  Priority:" << this->getThreadPriority() << endl;
                sleep(1);
            }
        }

    }
};

/*
 * 
 */
int main(int argc, char** argv)
{
    bool ret;
    MultiThread *mt;
    mt = new MultiThread();
    mt->Test();
    return (EXIT_SUCCESS);
}
====================================传说中的分割线=================================

PS:
1,还没有进行深入的测试,使用之前请进行必要的测试,以确保它符合你的要求。
2,如果你发现了 BUG,请联系我。 linux

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值