How can I detect a hang in QEventLoop?

前端 未结 2 824
日久生厌
日久生厌 2020-12-03 06:10

I am not sure if the title of my question is formulated correctly, so to explain what I really mean, consider the following example:

I create a QApplication

2条回答
  •  爱一瞬间的悲伤
    2020-12-03 06:56

    Some ideas, the actual solution really depends on what you need to do and what kind of feedback you need to have (a UI popping up? something recorded in logs? a debugging feature?)

    Use a QTimer and record the time between invocations of a slot of yours

    If the slot invocation is delayed by a significant w.r.t. the expected timer timeout, your event loop has been stuck somewhere. This will let you know there has been a problem, but won't tell you where it got stuck.

    Use a separate QThread

    Send periodically a signal to an object living in the main thread (or send an event; a cross-thread signal is implemented via events anyhow); the slot connected to that signal sends a signal back to the thread. If the "pong" takes too much (you can have a separate timer in the thread) do something -- abort(), raise(), i.e. an action which will cause a debugger to stop and you to see the main's thread stack trace, to deduce where you got stuck.

    Note that since you're running a separate thread you can't just pop up messageboxes or similar -- no UI in other threads! At most, log the event.

    Use a separate thread (2)

    Qt's event loop emits some signals (see QAbstractEventLoop), in theory you could attach to those in a separate thread and detect if control is not returning to it any more. Or, subclass QAEL to the same means.

    Use a QTcpServer / QLocalServer

    Same ping/pong concept, but using separate processes -- write a small TCP / local socket client which periodically sends a ping to your application, if the pong doesn't get back in a short while act (now you can also use an UI).

提交回复
热议问题