头文件Thread.h
#ifndef _THREAD_H_
#define _THREAD_H_
#include <pthread.h>
//抽象类
class Thread
{
public:
Thread();
virtual ~Thread();//虚析构函数
void Start();//线程的启动方法
void Join();//等待线程结束并且收回被等待线程的资源
void SetAutoDelete(bool autoDelete);
private:
static void* ThreadRoutine(void* arg);//线程入口函数 也是静态全局函数
virtual void Run() = 0;
//纯虚函数 //线程执行体run,通过继承类实现不同的线程函数run
pthread_t threadId_;//线程ID
bool autoDelete_;
};
#endif // _THREAD_H_
源文件Thread.cpp
#include "Thread.h"
#include <iostream>
using namespace std;
Thread::Thread() : autoDelete_(false)//构造函数
{
cout<<"Thread ..."<<endl;
}
Thread::~Thread() //析构函数
{
cout<<"~Thread ..."<<endl;
}
void Thread::Start()//启动线程
{
pthread_create(&threadId_, NULL, ThreadRoutine, this);
//第三个参数这里并不能直接放上执行函数run
//因为run函数式普通的成员函数,隐含的第一个参数是Thread*(就是this)
//调用的时候是thiscall约定,也就是说他不能做为入口函数
}
void Thread::Join() //等待线程执行结束并且收回被等待线程的资源
{
pthread_join(threadId_, NULL);
}
void* Thread::ThreadRoutine(void* arg)//
{
Thread* thread = static_cast<Thread*>(arg);//派生类指针转换成基类指针
thread->Run();
if (thread->autoDelete_)
delete thread;
return NULL;
}
void Thread::SetAutoDelete(bool autoDelete)
{
autoDelete_ = autoDelete;
}
测试文件Thread_test
#include "Thread.h"
#include <unistd.h>
#include <iostream>
using namespace std;
class TestThread : public Thread
{
public:
TestThread(int count) : count_(count)
{
cout<<"TestThread ..."<<endl;
}
~TestThread()
{
cout<<"~TestThread ..."<<endl;
}
private:
void Run()
{
while (count_--)
{
cout<<"this is a test ..."<<endl;
sleep(1);
}
}
int count_;
};
int main(void)
{
/*
TestThread t(5);
t.Start();
t.Join();
*/
TestThread* t2 = new TestThread(5);
t2->SetAutoDelete(true);
t2->Start();
t2->Join();
for (; ; )
pause();
return 0;
}
//CMake文件的编写
cmake_minimum_required(VERSION 2.6)
project(pas CXX)
set(CXX_FLAGS -g -Wall)
set(CMAKE_CXX_COMPILER "g++")
string(REPLACE ";" " " CMAKE_CXX_FLAGS "${CXX_FLAGS}")
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin)
add_executable(Thread_test Thread_test.cpp Thread.cpp)
target_link_libraries(Thread_test pthread)