c++ cpp 在类中执行线程 进行恒定计算

在编程中,顺序执行是常见的模式,但是对cpu的利用率不是很高,采用线程池,又太麻烦了,原因是还得不断地把任务拆分,扫描返回值。

如果 初始化n个类的时候,传递数据自身即可异步计算,那么是一个比较好的策略。

因此,我尝试在 类中开启一个线程

在这里插入图片描述

c++代码

#include <iostream>
#include <thread>
#include <chrono>
class threadrunclass {
public:
    threadrunclass() : log_num(0), running(true) {}

    void thread_run_fuc() {
        while (running) {
            std::this_thread::sleep_for(std::chrono::milliseconds(20));
            log_num++;
        }
    }

    int get_log_num() const {
        return log_num;
    }

    void start_thread() {
        std::thread th(&threadrunclass::thread_run_fuc, this);
        th.detach();
    }

    void stop_thread() {
        running = false;
    }
   ~threadrunclass() {
        stop_thread();
    }

private:
    int log_num;
    bool running;
};

class test_class{
public:
	threadrunclass obj = threadrunclass();
   test_class() {
        obj.start_thread();
    }
	int get_data_fuc(){
		return obj.get_log_num();
	}
};



int main(){
	test_class testobj = test_class();
    for (int i = 0; i < 5; i++) {
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
        std::cout << "tts: " << testobj.get_data_fuc() << std::endl;
    }
    std::cout<<"get_curr+num "<<testobj.get_data_fuc()<<std::endl;
}

// int main() {
//     threadrunclass myObject;
//     myObject.start_thread();

//     // 测试代码:每隔1秒获取一次log_num的值,共获取5次
//     for (int i = 0; i < 5; i++) {
//         std::this_thread::sleep_for(std::chrono::milliseconds(200));
//         std::cout << "log_num: " << myObject.get_log_num() << std::endl;
//     }

//     myObject.stop_thread();
//     return 0;
// }

模式的适用场景: 1.通讯场景 2.耗时计算

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值