2

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

JLev
  • 705
  • 1
  • 9
  • 30
  • Maybe you don't even need to stop the event loop. But having your own queue of messages of your *type* you can clean it. – Alexander V Jul 03 '17 at 15:10
  • Or you can implement an error state in your analysing thread. Once you are in an error state, you skip all (new) calculations. – m7913d Jul 03 '17 at 19:29

1 Answers1

1

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();
}
Steve Lorimer
  • 27,059
  • 17
  • 118
  • 213