c++multithreadingqtqeventloop

Recovering from error in Qt


I'm implementing a system that uses 3 threads (one is GUI, one is TCP client for data acquisition and one analysis thread for calculations). I'm having a hard time handling an exception for either one. The case that I'm trying to solve now is what happens if some calculation goes wrong, and I need to 'freeze' the system. The problem is that in some scenarios, I have data waiting in the analysis thread's event loop. How can I clear this queue safely, without handling all the events (as I said, something went wrong so I don't want any more calculations done). Is there a way to clear an event loop for a specific thread? When can I delete the objects safely?

Thanks


Solution

  • You question is somewhat low on details, but I assume you're using a QThread and embedding a QEventLoop in it?

    You can call QEventLoop::exit(-1), which is thread safe.

    The value passed to exit is the exit status, and will be the value returned from QEventLoop::exec(). I've chosen -1, which is typically used to denote an error condition.

    You can then check the return code from exec(), and act accordingly.

    class AnalysisThread : public QThread
    {
        Q_OBJECT
    public:
        void run() override
        {
            int res = _loop.exec();
            if (res == -1)
            {
                // delete objects
            }
        }
    
        void exit()
        {
            _loop.exit(-1);
        }
    private:
        QEventLoop _loop;
    };
    

    Elsewhere, in your exception handler

    try
    {
        // ...
    }
    catch(const CalculationError& e)
    {
        _analysis_thread.exit();
    }