c++ 直接接收异步异常

rsl1atfo  于 2023-01-06  发布在  其他
关注(0)|答案(1)|浏览(84)
class ClassA
{
    void running()
    {
        int count = 0;

        m_worker_stop.store(true);
        while (m_worker_stop.load() == false)
        {
            count++;
            if (count == 10)
            {
                // Make exception
                std::vector v(100000000000);
            }            
        }
    }

    void start()
    {
        m_worker = std::async(std::launch::async, &ClassA::running, this);
    }

    void stop()
    {
        m_worker_stop.store(true);
        if (m_worker.valid())
            m_worker.get();    // catch exception in this point
    }

    std::future<void>   m_worker;
    std::atomic_bool    m_worker_stop = { false };
}

class Main    // this is single-ton Main class
{
    ...
    void running()
    {
        try {
            m_classA->start();

            // Wait for external signal(ex. SIGINT, SIGTERM, ..)
            while (true) { // signal check }

            m_classA->stop();
        }
        catch(std::exception& e) {
            // re-create throwed object
        }
        catch(...) {
            // re-create throwed object
        }
    }
}

int main()
{
    Manager::getInstance()::running();
    return 0;
}

大家好,节目的大致结构如上。
事实上,我不仅有classA,还有许多其他对象,如B、C和D。(start()和stop()函数是类似的!)
使用**std::vector v(1000000..)**引发异常
但是,当stop()被激活时,它变成了一个捕获。
我实际上想要的是删除classA对象,并在发生异常时重新创建它。
所以我需要直接捕捉异常发生的时间。
在这种情况下,有没有办法不等待信号就获得异常?

46qrfjad

46qrfjad1#

以下是实现所需效果的一种方法:

class Main    // this is single-ton Main class
{
    ...
    void running()
    {
        for (size_t i = 0; i < max_tries; ++i)
        {
            try {
                m_classA->start();
                    // Wait for external signal(ex. SIGINT, SIGTERM, ..)
                while (true) { // signal check }
                m_classA->stop();

                // path to happy ending :)
                LOG("Main::running(): Operation successful.", 
                return;
            }
            catch(std::exception& e) {
                LOG("Main::running(): Exception caught: message:\"{}\"", e.what());
            }
            catch(...) {
                LOG("Main::running(): Unspecified exception caught, aborting.");
                return;  // Example of 'unrecoverable error'
            }
        
            // this part is only executed after an exception.
            m_classA->shut_down();   // if you need some special shut down after an error.
            m_classA.clear();        // this is redundant, but explicit (optional)
            m_classA = MakeMeAnA();  // call our favorite A construction method.
        }

        // path to total failure :(
        LOG("Main::running(): Exiting after {} failed attempts", max_tries);
    }

  private:
      static constexpr size_t max_tries = 3;
};

相关问题