qt线程与movetothread [英] qt thread with movetothread

查看:160
本文介绍了qt线程与movetothread的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用线程创建程序:
主循环开始。
当一个测试返回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方法如下:

 QThread *thread = new QThread( );
 Task    *task   = new Task();
 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( thread, SIGNAL(finished()), task, SLOT(deleteLater()) );
 connect( thread, SIGNAL(finished()), thread, SLOT(deleteLater()) );
 thread->start();

如果你不熟悉信号/插槽,Task类看起来像这样: p>

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:
    void doWork();
signals:
    void workFinished();
};

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆