#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
/*
public protected private
共有继承 public protected 不可见
私有继承 private private 不可见
保护继承 protected protected 不可见
*/
class Thread
{
protected:
pthread_t pid;
private:
static void * start_thread(void *arg);//静态成员函数
virtual void run() = 0;//基类中的虚函数要么实现,要么是纯虚函数(绝对不允许声明不实现,也不纯虚)
public:
int start();
};
int Thread::start()
{
if(pthread_create(&pid,NULL,start_thread,(void *)this) != 0)//创建一个线程(必须是全局函数)
{
return -1;
}
return 0;
}
void* Thread::start_thread(void *arg)//静态成员函数只能访问静态变量或静态函数,通过传递this指针进行调用
{
Thread *ptr = (Thread *)arg;
ptr->run(); //线程的实体是run
return ((void *)0);
}
class MyThread:public Thread
{
private:
int stop;
virtual void run();// virtual 可以省略
public:
MyThread();
~MyThread();
void print();
};
void MyThread::run()
{
for(;;)
{
printf(" run this = %p pid= %u pid=(0x%x)\n",this,pid,pid);
if(stop)
return;
sleep(1);
print();
}
}
void MyThread::print()
{
printf("hello world pid= %u pid=(0x%x) \n",pid,pid);
}
MyThread::MyThread()
{
printf("MyThread this = %p pid= %u pid=(0x%x) \n",this,pid,pid);
stop = 0;
}
MyThread::~MyThread()
{
void *ret;
printf(" ~MyThread this = %p pid= %u pid=(0x%x)\n",this,pid,pid);
stop = 1;
pthread_join(pid,&ret);
}
int main(int argc,char *argv[])
{
MyThread *test = new MyThread();
MyThread *test1 = new MyThread();
//基类的保护成员在派生类中为保护成员,派生类可见,派生类外不可见
//printf("test1->pid =(0x%x)\n",test1->pid);
test->start();
test1->start();
sleep(3);
delete test;
delete test1;
sleep(10);
return 0;
}
$ g++ thread_class.cpp -lpthread -std=c++11 -o test
$ ./test.exe
MyThread this = 0x600000360 pid= 848 pid=(0x350)
MyThread this = 0x6000003d0 pid= 894 pid=(0x37e)
run this = 0x600000360 pid= 371200 pid=(0x5aa00)
run this = 0x6000003d0 pid= 371456 pid=(0x5ab00)
hello world pid= 371456 pid=(0x5ab00)
hello world pid= 371200 pid=(0x5aa00)
run this = 0x6000003d0 pid= 371456 pid=(0x5ab00)
run this = 0x600000360 pid= 371200 pid=(0x5aa00)
hello world pid= 371456 pid=(0x5ab00)
hello world pid= 371200 pid=(0x5aa00)
run this = 0x6000003d0 pid= 371456 pid=(0x5ab00)
run this = 0x600000360 pid= 371200 pid=(0x5aa00)
~MyThread this = 0x600000360 pid= 371200 pid=(0x5aa00)
hello world pid= 371200 pid=(0x5aa00)
hello world pid= 371456 pid=(0x5ab00)
run this = 0x600000360 pid= 371200 pid=(0x5aa00)
run this = 0x6000003d0 pid= 371456 pid=(0x5ab00)
~MyThread this = 0x6000003d0 pid= 371456 pid=(0x5ab00)
hello world pid= 371456 pid=(0x5ab00)
run this = 0x6000003d0 pid= 371456 pid=(0x5ab00)