[英]Why won't my nested QEventLoop deliver all the events for my QThread?
我在使用QEventLoop時遇到問題。 我想為單元測試創建一個“ TimeBoundExerciser”,以使在QEventLoop上阻止的SUT不會阻止其余的測試用例。 具體來說,我的測試用例是確保SUT在超時后終止。
TimeBoundExerciser基本上產生一個線程,在該線程上執行SUT,等待該線程終止,如果在特定時間后仍未終止,則通過QMetaObject :: invokeMethod()在該線程上調用quit()方法。 )和QueuedConnection。 我希望執行quit()會導致嵌套的QEventLoop退出,從而終止我的線程。 但是,我發現,永遠不會調用quit()方法,並且線程永遠不會終止。 我的TimeBoundExerciser的代碼如下:
class IExerciseTheSystem
{
void operator()() = 0;
};
class TimeBoundExerciser : private QThread
{
Q_OBJECT
public:
enum CompletionType
{
TERMINATED,
FORCE_QUIT,
QUIT
};
TimeBoundExerciser(const IExerciseTheSystem& exerciser);
CompletionType exercise(unsigned long timeoutMillis);
protected:
void run();
protected slots:
void exerciseTheSystem();
private:
const IExerciseTheSystem& exerciser;
};
TimeBoundExerciser::TimeBoundExerciser(const IExerciseTheSystem& exerciser) : exerciser(exerciser)
{
}
TimeBoundExerciser::CompletionType TimeBoundExerciser::exercise(unsigned long timeoutMillis)
{
start();
while (!isRunning())
{
msleep(10);
}
moveToThread(this);
wait(timeoutMillis);
if (!isFinished())
{
bool quitResult;
QMetaObject::invokeMethod(this, "quit", Qt::QueuedConnection, Q_RETURN_ARG(bool, quitResult));
wait();
return FORCE_QUIT;
}
return QUIT;
}
void TimeBoundExerciser::run()
{
setTerminationEnabled(true);
QMetaObject::invokeMethod(this, "exerciseTheSystem", Qt::QueuedConnection);
exec();
}
void TimeBoundExerciser::exerciseTheSystem()
{
cout << "Starting exerciser" << endl;
exerciser();
cout << "Exerciser ended" << endl;
}
exercise()方法在主線程上執行,以啟動整個過程。
如果測試運行時間過長,則可能是某種形式的循環處理數據。
當然,由於測試線程正忙於運行測試,因此不會發出您的退出請求。 消息不會中斷線程,當線程完成對上一條消息的處理並恢復事件循環時,將對其進行處理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.