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


最近在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,线程的控制有待完善,这个阿,暂时没有时间研究。
  • 1
  • 2
  • 下一页

相关内容