C++ 编写多线程类 类的多线程封装

本文介绍了一种在C++中自定义多线程类的方法,该类能够自动创建与回收线程,支持线程的启动与停止操作。通过具体的代码实现,展示了如何利用pthread库进行线程管理,适用于需要在C++应用中加入多线程功能的开发者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值