将QObjects移入QThreads

时间:2018-09-16 04:49:42

标签: c++ qt qthread

基本上,标题...如果没有QThread(或仅被注释),我得到以下结果:

LOG> Log working!
LOG> PRODUCER: sent resource address: 29980624
PRODUCER: sent resource address: 29980624
CONSUMER: received resource address: 29980624

29980624或任何相关的内存位置。

但是,只要不加评论

LOG> Log working!

mainwindow.h

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

public slots:
    void slot_log(QString str);

signals:
    void signal_log(QString str);

private:
    void createConsumer( void );
    void deleteConsumer( void );
    void createProducer( void );
    void deleteProducer( void );
    void createConnections( void );
    SingleConsumer *consumer;
    QThread *thread_consumer;
    SingleProducer *producer;
    QThread *thread_producer;
};

mainwindow.cpp

#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
{
    createConsumer();
    createProducer();
    createConnections();
    QTimer::singleShot(1000, producer, SLOT(slot_publishResourceAddress()) );
}

void MainWindow::slot_log(QString str)
{
    qWarning( QString("LOG> %1").arg(str).toUtf8() );
}

void MainWindow::createConnections( void )
{
    connect(this, SIGNAL(signal_log(QString)), this, SLOT(slot_log(QString)));
    emit signal_log(QString("Log working!"));

    connect(producer, SIGNAL(signal_resourceAddress(uint_fast8_t*)), consumer, SLOT(slot_resource(uint_fast8_t*)));
}

void MainWindow::createProducer( void )
{
     producer = new SingleProducer();
     thread_producer = new QThread();
     producer->moveToThread(thread_producer); // THIS LINE DESERVES ATTENTION
     connect(producer, SIGNAL(signal_log(QString)), this, SLOT(slot_log(QString)));
}

singleproducer.h

#ifndef SINGLEPRODUCER_H
#define SINGLEPRODUCER_H

#include <QWidget>

class SingleProducer : public QObject
{
    Q_OBJECT
public:
    explicit SingleProducer(QObject *parent = nullptr);

signals:
    void signal_resourceAddress( uint_fast8_t* addr );
    void signal_log(QString str);
public slots:

    void slot_publishResourceAddress( void )
    {
        emit signal_log( QString("PRODUCER: sent resource address: %1").arg((long int) &un_resources__) );
        qWarning(QString("PRODUCER: sent resource address: %1").arg((long int) &un_resources__).toUtf8());
        emit signal_resourceAddress( &un_resources__ );
    }


private:
    uint_fast8_t un_resources__;
};

#endif // SINGLEPRODUCER_H

编辑器不允许我发布更多代码...但是我认为这是最相关的部分...如果没有,请告诉我。但我在pastebin

分享了

我的错误在哪里?

1 个答案:

答案 0 :(得分:2)

QThreadMainWindow::createProducer中创建MainWindow::createConsumer之后,您实际上忘记了启动QThread。来自documentation of the constructor of QThread

  

构造一个新的thread_producer->start()来管理一个新线程。父级拥有QThread的所有权。 直到调用start(),线程才开始执行。

因此,您要做的就是在创建线程之后分别调用thread_consumer->start()StorageFile