C++ 編寫多線程類 類的多線程封裝

  1. 在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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章