Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 .

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
510 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...