Basically, the title... if there is no QThread (or it is just commented) I get the following result:
LOG> Log working!
LOG> PRODUCER: sent resource address: 29980624
PRODUCER: sent resource address: 29980624
CONSUMER: received resource address: 29980624
29980624, or any relevant memory position.
But, when un-commented just
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
The editor doesn't let me post more code... but I think that this is the most relevant part... if not, let me know. But I shared it at pastebin
Where is my mistake?
You forgot to actually start the QThread
s after creating them in both MainWindow::createProducer
and MainWindow::createConsumer
. From the documentation of the constructor of QThread
:
Constructs a new
QThread
to manage a new thread. The parent takes ownership of the QThread. The thread does not begin executing until start() is called.
So all you need to do is call thread_producer->start()
and thread_consumer->start()
respectively after creating the threads.