封装完以下这个初级版本 主要发现这几点问题:
代码如下:
#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();
}
总的来讲 封装的不好 下一次贴上可能要考虑的因素 以及改进版本