[英]How to synchronize between main and worker thread in Qt?
I have this design.我有这个设计。 I could not achieve what I need:我无法实现我所需要的:
My goal is restart(re-run) to "worker" thread when it has finished its task.我的目标是在完成任务后重新启动(重新运行)到“工作”线程。 I intend to call the worker thread destructor for this approach because, it takes memory from heap.我打算为此方法调用工作线程析构函数,因为它从堆中获取内存。 I need to clean-up all the related variables.我需要清理所有相关变量。
How can I achieve this?我怎样才能做到这一点?
int main()
{
// re-start start
A* worker = B::getInstance();
worker->start();
// re-start end
return a.exec();
}
Writing a for-loop is not a solution.编写 for 循环不是解决方案。 Because, I need to learn worker thread is stopped completely.因为,我需要学习工作线程完全停止。 I tried using worker->wait().我尝试使用 worker->wait()。 But it does not work.但它不起作用。
如何使用QThread
的信号finished()
?
I don't fully understand your question, but if you allocate the thread and you have to restart it again once it's completed, you can do the following:我不完全理解你的问题,但是如果你分配了线程并且你必须在它完成后重新启动它,你可以执行以下操作:
to check:去检查:
to restart:重启:
The general rule in RAII (Resource Acquisition Is Initialization) is that the code that acquires a resource is responsible for ensuring it is released. RAII(Resource Acquisition Is Initialization)中的一般规则是,获取资源的代码负责确保它被释放。 Thus, your worker thread should terminate after releasing all resources it has acquired.因此,您的工作线程应该在释放它获得的所有资源后终止。
The general style of the main program will be:主程序的一般风格将是:
Alternatively, the main thread can still run in the forever loop, but recognizes when a delegatable task has arrived and at that point, initialize the worker thread and give it the specific task.或者,主线程仍然可以在永久循环中运行,但会识别可委托任务何时到达,然后初始化工作线程并为其分配特定任务。 This allows for as many worker threads as there are incomplete delegatable tasks.这允许与不完整的可委托任务一样多的工作线程。 You might need to throttle the number so that you don't have too many incomplete tasks.您可能需要限制数量,以免有太多未完成的任务。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.