LINUX多线程 封装

封装完以下这个初级版本  主要发现这几点问题:

线程架构的封装:
 1)    封装如果没有外界穿入的参数越多,就越偏向C  达不到封装的目的。
2)   函数指针问题 pthread_create要求的线程函数为  void*(* threadroutinue) (void * )类型 用户态的线程函数都是不同的            类型,如果 pthread_create封装在类中,而用户线程函数没有放入   在c++的编译中会报错,如果要采用线程函数的定义声明都是在类外实行,目前看来只有2种解决方案:
    a)  编译器里加上 -fpermissve选项  忽略实参到形参的类型转换   【这点想了好久
    b) 在 自己的用户态函数下  加上一个reinterpret_cast<void* (* )(void*) >  转换符号 才能绕开 编译器

这2点解决方式对于封装来讲  都不是比较好的选择  给使用者太多的限制条件
发火

代码如下:




#include <iostream>
#include <string>
#include <unistd.h>
#include <pthread.h>
using namespace std;
#include "Thread.h"
namespace SFWTOMS
{
Thread::Thread(ThreadFunc threadFus):threadFu(threadFus)
{
}
int Thread::start()
{
//线程开始函数
int status;
if((status=pthread_create(&pthreadID,NULL,threadFu,NULL))!=0)
{
//如果没有创建成功  是否改抛出异常~?
cout<<"没有创建成功~!"<<endl;
}
return 0;
}
int Thread::Join()
{
int status;
if((status=pthread_join(pthreadID,&arg))!=0)
{
//如果没有加入进去 应该也是需要抛出异常的
}
return status;
}
void Thread::Sleep(int time)
{
sleep(time);
}
Thread::~Thread()
{
//防止异常终止  可以安排在析构时调用detach
 try
 {
 Detach();
 }catch(int)
 {
 //吞掉异常
 }
}
int Thread::Detach()
{
int status;
if((status=pthread_detach(pthread_self()))!=0)
{
//抛出detach异常
}
return status;
}
}


#include <iostream>
#include<string>
#include <pthread.h>
#ifndef THREAD_H_
#define THREAD_H_
using namespace std;
namespace SFWTOMS
{


typedef void* (*ThreadFunc)(void *);
class Thread
{
public:
//Thread构造函数 threadFu是入口函数 threadName是线程的名字
//这本身不属于pthread范围内的
Thread(ThreadFunc);
//返回的状态作为一个是否创建成功
virtual int start();
virtual ~Thread();
int Detach();
int Destroy();
//加入到主线程里 等待本线程pthreadID线程完成以后
int Join();
void Sleep(int);
//线程属性函数
inline pthread_t Get_thread_ID() const
{
return pthreadID;
}


private:


//线程函数指针
ThreadFunc threadFu;
//线程的id号
pthread_t pthreadID;
//线程的名字
string threadName;
//线程属性
pthread_attr_t* attr;
//线程函数传进去的参数
void *arg;
private:
//用户线程函数
 template<typename T,typename U> static T Routinue(U);




};
}




#endif /* THREAD_H_ */




测试函数:





#include <iostream>
#include "Thread.h"
using namespace std;
int* threadfun(int *a)
{
cout<<"first thread~!"<<endl;
return NULL;
}
int main()
{
string threadname="this";
SFWTOMS::Thread thread(reinterpret_cast<void*(*)(void*)>(threadfun));
//线程开始执行
cout<<"准备执行"<<endl;
thread.start();
//阻塞其线程
thread.Join();
}

总的来讲    封装的不好  下一次贴上可能要考虑的因素  以及改进版本

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值