在编程中,顺序执行是常见的模式,但是对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.耗时计算



















