問(wèn)題描述
我正在嘗試使用線程創(chuàng)建程序:主要以一個(gè)循環(huán)開始.當(dāng)測(cè)試返回 true 時(shí),我創(chuàng)建一個(gè)對(duì)象,并希望該對(duì)象在另一個(gè)線程中工作然后返回并開始測(cè)試.
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();
問(wèn)題是當(dāng)我啟動(dòng)新線程時(shí),主線程停止并等待新線程完成.
the problem is when i start the new thread the main thread stops and wait for the new thread's finish .
推薦答案
規(guī)范的 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();
如果您不熟悉信號(hào)/插槽,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();
};
這篇關(guān)于帶有 movetothread 的 qt 線程的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!