暂停和恢复 QThread
我最近开始学习 QThreads,并且我有一个程序在单独的线程中运行 4 小时长的循环(以便我可以继续使用 GUI)。我所追求的是,当用户单击暂停 qpushbutton 时,将暂停/挂起线程,并且当用户单击恢复 qpushbutton 时,程序应该恢复。我怎样才能实现这个目标?
我正在考虑从我的主类发送信号;但是,我不确定如何在线程中处理它们。是否可以在线程中处理从主类发送的信号?目前,我有线程向主类发出信号,并且工作正常,但我不确定如何从主类发送线程并在线程中接收它们。
I've recently began learning about QThreads and I've a program which runs a 4 hours long loop in a separate thread (so that I may continue to use the GUI). What I am after is, something that will pause/suspend the thread when the user clicks pause qpushbutton, and when the user clicks the resume qpushbutton, the program should resume. How may I achieve this?
I was thinking of sending signals from my main class; however, I'm not sure how I can handle them in the thread. Is it possible to handle signals sent from the main class in a thread? Currently, I have the thread emitting signals to the main class, and that works fine, but I'm not sure how to go about sending threads from the main class, and receiving them in the thread.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好的,所以我建议您创建内部线程变量,该变量将在循环的每个步骤中进行检查 + QWaitCondition 来恢复它。
QWaitCondition
(参见Qt文档)来暂停线程执行Create恢复方法,您将在其中关闭“暂停字段”并唤醒 QWaitCondition
Ok, so I suggest you make internal thread variable that will be checked in each step of your loop +
QWaitCondition
to resume it.QWaitCondition
(see Qt docs) to pause thread executionCreate resume method where you will switch off "pause field" and wake QWaitCondition
为了暂停工作线程,我使用了以下方法。
这是我的 GUI.h 文件的一部分:
这是我的 GUI.cpp 文件的一部分:
这是我的worker.h 文件的一部分:
这是我的worker.cpp 文件的一部分:
基本思想是使用 QAtomicInt 特殊功能。在工作线程中,我们检查 CHECK 是否未更改。如果它被改变了,我们返回并且什么都不做。要更改它,我们必须与工作线程竞争从 GUI 线程访问 CHECK。这就是为什么我们需要 while 块。我们将 while 块放在简历部分,尽管在大多数情况下,第一次尝试就会成功。但我们正在处理多线程,还记得吗?
To suspend a working thread I used the following approach.
Here is a part of my GUI.h file:
Here is a part of my GUI.cpp file:
Here is my worker.h file:
Here is a part of my worker.cpp file:
The basic idea is to use QAtomicInt special features. In the worker thread we check if CHECK is unchanged. If it was changed we return and do nothing. To change it we have to compete with the worker thread for access to CHECK from the GUI thread. That is why we need while block. We put while block in the resume section, though in most cases it will succeed with the first attempt. But we are dealing with multi-threading, remember?