简体   繁体   English

使用QThread运行可管理后台线程的正确方法

[英]Proper way to run managable background thread with QThread

I need to run few background threads which must be managable in a way that I can safely stop it anytime. 我需要运行一些后台线程,这些后台线程必须是可管理的,以便可以随时安全地停止它。 Threads should do some repetable task. 线程应该执行一些重复的任务。

I read documentation and the best way which I can find is to subclass QThread and reimplement run() method: 我阅读了文档,发现的最佳方法是将QThread子类化并重新实现run()方法:

class BackgroundThread: public QThread
{
   Q_OBJECT

   virtual void run() Q_DECL_OVERRIDE
   {
       while (true)
       {
          // do some routine task
          // sleep ...
       }  
   }
};

I like this because I can run code in separate thread and I don't need to do unconvient Qt magic with moveToThread and connecting up to 10 signals/slots to properly manage thread resources. 我之所以喜欢这样,是因为我可以在单独的线程中运行代码,而我不需要通过moveToThread进行不灵活的Qt魔术操作,并且最多可以连接10个信号/插槽来正确管理线程资源。

The problem is that I can't find a way to safely stop the thread. 问题是我找不到安全停止线程的方法。 I don't want to terminate it in a random place of execution, I would want it to stop when next iteration ends. 我不想在随机执行的地方终止它,我希望它在下一次迭代结束时停止。 The only way to achive it which I see now is to add some atomic flag to thread class and set it from main thread when I need to stop it, but I really don't like this solution. 我现在看到的实现它的唯一方法是在线程类中添加一些原子标记,并在需要停止它时从主线程中对其进行设置,但是我真的不喜欢这种解决方案。

What is the best way to implement managable background thread using Qt5? 使用Qt5实现可管理后台线程的最佳方法是什么?

You don't need any magic and "10 signals/slots". 您不需要任何魔术和“ 10个信号/插槽”。 Just create your worker: 只需创建您的工人:

class Worker: public QObject
{
    ...
public slots:
    void routineTask();
}

Somewhere in your code: 在代码中的某处:

QThread bckgThread;
bckgThread.start();
Worker worker;
worker.moveToThread(&bckgThread);

Connect some signal to the routineTask slot to call it or use QMetaObject::invokeMethod . 将一些信号连接到routineTask插槽以调用它或使用QMetaObject::invokeMethod And when you are done with the thread, just call: 当您完成线程处理后,只需调用:

bckgThread.quit();
bckgThread.wait();

That's pretty simple pattern. 那是非常简单的模式。 Why go the hard way and subclass QThread ? 为什么要艰难地QThread子类?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM