linux C++ 面向对象线程类(封装,继承,多态)

头文件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)



  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值