- 在C++开发中,每个类均是一个对象,讲系统分化为对象开发能使系统结构清晰明了。但是C++原生开发中因为没有现成的多线程类可以继承,因此有必要自己写一个多线程的类,要求足够独立,自动创建与回收线程,线程可以执行开始,停止操作,故此总结网上现有资源,自己写了一个简单的多线程类。
h文件
#ifndef APPSERVE_H
#define APPSERVE_H
#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <thread>
using namespace std;
class AppServe
{
public:
AppServe();
~AppServe();
void Start();
void Stop();
static void *run(void*__this);
public:
pthread_t AppServe_pthread;//线程句柄
pthread_mutex_t AppServe_mut;//线程锁
int AppServe_threadExit=-1;//线程退出标志
};
#endif // APPSERVE_H
cpp文件
#include "appserve.h"
AppServe::AppServe()
{
pthread_mutex_init(&AppServe_mut,NULL);
}
//资源释放
AppServe::~AppServe(){
Stop();
}
//启动线程
void AppServe::Start(){
AppServe_threadExit=1;
if(pthread_create(&AppServe_pthread, NULL,run,this))
{
printf("pthread_create error!\n");
return;
}
}
//停止线程
void AppServe::Stop(){
AppServe_threadExit=0;
pthread_join(AppServe_pthread,NULL);
}
void* AppServe::run(void* __this){
AppServe * _this=(AppServe *)__this;
while (_this->AppServe_threadExit) {
printf("abb\r\n");
sleep(1);
}
}
简单使用main文件
#include <iostream>
using namespace std;
int main()
{
AppServe abc;
abc.Start();
cout << "Hello World!" << endl;
sleep(5);
abc.Stop();
sleep(10);
return 0;
}