thread.h

#ifndef _THREAD_H
#define _THREAD_H
#include<pthread.h>

class Thread
{
public:
    Thread();
    virtual ~Thread();
    void Start();
    void Join();
private :
    static void* TreadRoutine(void* arg);
    virtual void Run() = 0;
    pthread_t thread_id;
};
#endif

thread.cpp

#include"thread.h"
#include<iostream>
using namespace std;
Thread::Thread()
{
    cout << "Thread" << endl;
}
Thread::~Thread()
{
    cout << "~Thread" << endl;
}
void Thread::Start()
{
    pthread_create(&thread_id, NULL, TreadRoutine, this);//this指针是派生类
//pthread_create函数调用的函数必须得是一个静态函数,因为类内函数不能调用类内函数
} void Thread::Join() { pthread_join(thread_id, NULL); } void* Thread::TreadRoutine(void* arg) { Thread* thread = static_cast<Thread*>(arg);//将派生类指针转换成基类指针 thread->Run();
//delete thread;可以delete的前提是派生类是new出来的,虽然thread是基类的指针,但是因为析构函数是虚函数,所以可以调用到派生类的析构函数。
return NULL; }

test_thread.cpp

#include "thread.h"
#include<unistd.h>
#include<iostream>
using namespace std;
class TestThread :public Thread
{
public:
    TestThread(int count) :count_(count)
    {
        cout << "test thread...." << endl;
    }
    ~TestThread()
    {
        cout << "~ test thread..." << endl;
    }
    void Run()
    {
        while (count_--)
        {
            cout << "this is a test  ... " << endl;
            sleep(1);
        }
    }
    int count_;
};
int main()
{
    TestThread t(5);
    t.Start();
    t.Join();
    return 0;
}

运行过程是

创建一个派生类t,派生类中自动创建一个pthread_id

之后调用start函数创建线程,线程中调用静态函数来调用我们想实现的功能,静态函数中调用run,这个在派生类中实现的纯虚函数。

 

 

如果想要线程和线程对象一起消亡,那么可以在静态函数中delete掉对象。