带有 movetothread 的 qt 线程

时间:2022-12-30
本文介绍了带有 movetothread 的 qt 线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在尝试使用线程创建程序:主要以一个循环开始.当测试返回 true 时,我创建一个对象,并希望该对象在另一个线程中工作然后返回并开始测试.

I'm trying to create a program using threads: the main start with a loop. When a test returns true, I create an object and I want that object to work in an other thread then return and start the test .

QCoreApplication a(argc, argv);
while(true){
    Cmd cmd;
    cmd =db->select(cmd);
    if(cmd.isNull()){ 
        sleep(2);  
        continue ;
    }
    QThread *thread = new QThread( );
    process *class= new process ();
    class->moveToThread(thread);
    thread->start();

    qDebug() << " msg"; // this doesn't run until  class finish it's work 
}
return a.exec();

问题是当我启动新线程时,主线程停止并等待新线程完成.

the problem is when i start the new thread the main thread stops and wait for the new thread's finish .

推荐答案

规范的 Qt 方式如下所示:

The canonical Qt way would look like this:

 QThread* thread = new QThread( );
 Task* task = new Task();

 // move the task object to the thread BEFORE connecting any signal/slots
 task->moveToThread(thread);

 connect(thread, SIGNAL(started()), task, SLOT(doWork()));
 connect(task, SIGNAL(workFinished()), thread, SLOT(quit()));

 // automatically delete thread and task object when work is done:
 connect(task, SIGNAL(workFinished()), task, SLOT(deleteLater()));
 connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));

 thread->start();

如果您不熟悉信号/插槽,Task 类将如下所示:

in case you arent familiar with signals/slots, the Task class would look something like this:

class Task : public QObject
{
Q_OBJECT
public:
    Task();
    ~Task();
public slots:
    // doWork must emit workFinished when it is done.
    void doWork();
signals:
    void workFinished();
};

这篇关于带有 movetothread 的 qt 线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:为 Visual Studio 2012 编译 Qt 4.8.x 下一篇:使用 () 或不使用 () 创建对象的区别

相关文章

最新文章