在C ++中创建可以正常终止的监视器类

我的主要功能加载了一个监控类。此类调用外部服务以定期获取一些数据并报告运行状况。

这些是下面的类中的task_1和task_2,可以具有子任务。任务累积一些值,这些值存储到共享的“ Data”类中。

因此,每个task_N都与一个线程耦合,该线程执行,休眠一段时间并永久执行直到程序停止。 我的基本问题是我无法停止Monitor类中的线程,因为它们可能正在等待计时器到期(休眠)

#include <iostream>
#include <thread>
#include <utility>
#include "Settings.hpp"
#include "Data.hpp"

class Monitors {

public:

    Monitors(uint32_t timeout1,uint32_t timeout2,Settings settings,std::shared_ptr<Data> data)
            : timeout_1(timeout1),timeout_2(timeout2),settings_(std::move(settings)),data_(std::move(data)) {}


    void start() {
        thread_1 = std::thread(&Monitors::task_1,this);
        thread_2 = std::thread(&Monitors::task_2,this);
        started_ = true;
    }

    void stop() {
        started_ = false;
        thread_1.join();
        thread_2.join();
        std::cout << "stopping threads" << std::endl;

    }

    virtual ~Monitors() {

        std::cout << "Monitor stops" << std::endl;
    }

private:

    void subtask_1_1() {
        //std::cout << "subtask_1_1 reads " << settings_.getWeb1() << std::endl;
    }

    void subtask_1_2() {
        //std::cout << "subtask_1_2" << std::endl;
        data_->setvalue1(21);
    }

    void task_1() {

        while(started_) {
            subtask_1_1();
            subtask_1_2();
            std::this_thread::sleep_for(std::chrono::milliseconds(timeout_1));
            std::cout << "task1 done" << std::endl;
        }

    }

    void subtask_2_1() {
        //std::cout << "subtask_2_1" << std::endl;
    }

    void subtask_2_2() {
        //std::cout << "subtask_2_2" << std::endl;
    }

    void task_2() {

        while(started_) {
            subtask_2_1();
            subtask_2_2();
            std::this_thread::sleep_for(std::chrono::milliseconds(timeout_2));
            std::cout << "task2 done" << std::endl;
        }

    }


private:

    bool started_ {false};
    std::thread thread_1;
    std::thread thread_2;
    uint32_t timeout_1;
    uint32_t timeout_2;
    Settings settings_;
    std::shared_ptr<Data> data_;

};

主要功能在这里:

        auto data = std::make_shared<Data>(10,20);
        Settings set("hello","world");
        Monitors mon(1000,24000,set,data);
        mon.start();

        int count = 1;
        while(true) {

            std::this_thread::sleep_for(std::chrono::milliseconds(1000));
            std::cout << data->getvalue2() << " and count is " << count << std::endl;
            count++;
            if ( count == 10)
                break;
        }
        std::cout << "now I am here" << std::endl;
        mon.stop();
        return 0;

现在,当我调用mon.stop()时,主线程仅在计时器运行时停止。 如何正常调用mon.stop()并中断并调用task_N?

更新:由于我不想调用std :: terminate,这是在c ++中实现监视器类的正确方法

yjyyjywww 回答:在C ++中创建可以正常终止的监视器类

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3145090.html

大家都在问