Lección 83-Otra forma de crear hilos (recomendado)

"Tutorial de análisis de experimentos Qt" - Lección 83 Erratas
Es un patrón de diseño común para realizar clases de subprocesos múltiples en Qt a través del método de combinación , y su principio es directamente
En respuesta a la señal de iniciado () , ejecute la función del cuerpo del hilo especificado (función de ranura tmain () ) en el hilo hijo .
AnotherThread :: AnotherThread ( QObject * padre):
QObject (padre)
{
moveToThread (& m_thread);
conectar (& m_thread, SIGNAL (iniciado ()), esto, SLOT (tmain ()));
}
Después de Qt4, la función QThread :: exec () se llama por defecto en la función QThread :: run () ;
Por lo tanto, la función tmain () (función del cuerpo del hilo) entrará directamente en el ciclo de eventos después de la ejecución, haciendo que el hilo sea para siempre
No puede finalizar automáticamente. La solución a este problema es llamar al final de la función tmain ()
La función QThread :: quit () finaliza activamente el ciclo de eventos del hilo.
anular AnotherThread :: tmain ()
{
/ * cuerpo de entrada del hilo * /
m_thread.quit (); // IMPORTANTE !!!
}
En el video, debido a negligencia, olvidé llamar a la función tmain () al escribir
La función QThread :: quit () hace que el objeto del hilo no se destruya.

 

 

 

 

 

 

 

 

 

 

 

#include <QtCore/QCoreApplication>
#include <QDebug>
#include <QThread>
#include "AnotherThread.h"

void test()
{
    AnotherThread at;

    at.start();
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    qDebug() << "main() tid = " << QThread::currentThreadId();

    test();
    
    return a.exec();
}

 

 

#ifndef ANOTHERTHREAD_H
#define ANOTHERTHREAD_H

#include <QObject>
#include <QThread>

class AnotherThread : public QObject
{
    Q_OBJECT

    QThread m_thread;
protected slots:
    void tmain();
public:
    explicit AnotherThread(QObject *parent = 0);
    void start();
    void terminate();
    void exit(int c);
    ~AnotherThread();
    
};

#endif // ANOTHERTHREAD_H
#include "AnotherThread.h"
#include <QDebug>

AnotherThread::AnotherThread(QObject *parent) :
    QObject(parent)
{
    moveToThread(&m_thread);

    connect(&m_thread, SIGNAL(started()), this, SLOT(tmain()));
}

void AnotherThread::tmain()
{
    qDebug() << "void AnotherThread::tmain() tid = " << QThread::currentThreadId();

    for(int i=0; i<10; i++)
    {
        qDebug() << "void AnotherThread::tmain() i = " << i;
    }

    qDebug() << "void AnotherThread::tmain() end";

    m_thread.quit();
}

void AnotherThread::start()
{
    m_thread.start();
}

void AnotherThread::terminate()
{
    m_thread.terminate();
}

void AnotherThread::exit(int c)
{
    m_thread.exit(c);
}

AnotherThread::~AnotherThread()
{
    m_thread.wait();
}

 

Supongo que te gusta

Origin blog.csdn.net/qq_26690505/article/details/108782288
Recomendado
Clasificación