把对线程操作封装在父类中(CBaseThread)。如:线程的初始化、启动、停止、参数管理等在父类中实现。在开发多线程程序时,只要继承自CBaseThread,把需要线程处理的业务代码放到Run函数中即可。这样封装后,线程开发者只需关注线程的业务处理逻辑,无需开发线程操作的代码,使开发变得简单。线程操作的函数也尽可能得到复用。以下代码供参考!
线程父类的代码如下:
//base_thread.h
#ifndef BASE_THREAD_H__
#define BASE_THREAD_H__
#include <thread>
class CBaseThread
{
public:
CBaseThread();
virtual ~CBaseThread();
public:
void Init(void *lpParameter);
void Start();
void Stop();
void SetThreadNum(int32_t nThreadNum);
int32_t GetThreadNum() const;
protected:
virtual void Run(void *lpParameter);
private:
void ThreadProc();
private:
std::thread m_tThread;
bool m_bRunFlag = true;
int32_t m_nThreadNum = 0;
void *m_lpParameter= nullptr;
};
#endif
//base_thread.cpp
#include "base_thread.h"
CBaseThread::CBaseThread()
{
}
CBaseThread::~CBaseThread()
{
}
void CBaseThread::Init(void *m_lpParameter)
{
m_lpParameter = m_lpParameter;
}
void CBaseThread::Start()
{
m_bRunFlag = true;
m_tThread = std::thread(&CBaseThread::ThreadProc, this);
}
void CBaseThread::Stop()
{
m_bRunFlag = false;
m_tThread.join();
}
void CBaseThread::SetThreadNum(int32_t nThreadNum)
{
m_nThreadNum = nThreadNum;
}
int32_t CBaseThread::GetThreadNum() const
{
return m_nThreadNum;
}
void CBaseThread::ThreadProc()
{
while(m_bRunFlag)
{
Run(m_lpParameter);
}
}
void CBaseThread::Run(void *lpParameter)
{
}
线程业务实现类示例如下:
//test_thread.h
#ifndef TEST_THREAD_H
#define TEST_THREAD_H
#include "base_thread.h"
class CTestThread : public CBaseThread
{
public:
CTestThread();
virtual ~CTestThread();
public:
virtual void Run(void *lpParameter);
};
#endif
//test_thread.cpp
#include "test_thread.h"
#include <iostream>
using namespace std;
CTestThread::CTestThread()
{
}
CTestThread::~CTestThread()
{
}
void CTestThread::Run(void *lpParameter)
{
static int i = 0;
cout << i++ << endl;
}
//测试主函数
//test.cpp
#include "test_thread.h"
#include <unistd.h>
int main()
{
CTestThread tth;
tth.Start();
sleep(5);
tth.Stop();
return 0;
}
编译:
g++ -o test *.cpp -std=c++11 -lpthread
运行:
./test