简体   繁体   English

带有movetothread的qt线程

[英]qt thread with movetothread

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 . 当测试返回true时,我创建一个对象,我希望该对象在另一个线程中工作,然后返回并开始测试。

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 . 问题是,当我启动新线程时,主线程停止并等待新线程的完成。

The canonical Qt way would look like this: 规范的Qt方式如下所示:

 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();

in case you arent familiar with signals/slots, the Task class would look something like this: 如果你不熟悉信号/槽,Task类看起来像这样:

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

I don't know how you structured your process class, but this is not really the way that moveToThread works. 我不知道你是如何构建你的进程类的,但这并不是moveToThread的工作方式。 The moveToThread function tells QT that any slots need to be executed in the new thread rather than in the thread they were signaled from. moveToThread函数告诉QT任何槽都需要在新线程中执行,而不是在它们发出信号的线程中执行。 (edit: Actually, I now remember it defaults to the tread the object was created in) (编辑:实际上,我现在记得它默认为创建对象的步骤)

Also, if you do the work in your process class from the constructor it will not run in the new thread either. 此外,如果从构造函数在流程类中完成工作,它也不会在新线程中运行。

The simplest way to have your process class execute in a new thread is to derive it from QThread and override the run method. 让进程类在新线程中执行的最简单方法是从QThread派生它并覆盖run方法。 Then you never need to call move to thread at all. 然后你根本不需要调用move to thread。

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

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