Hello! I am new to QT, I almost never worked with streams before, I would like to make inquiries about how to use streams correctly, in parallel, I read quite a lot, I’m not sure what I’m going to digest ...
Here is an example: there is a class identificator, .h:
class identificator:public QObject { Q_OBJECT public: identificator(); virtual ~identificator(); private: int id; private slots: void printID(); public: void setID(int i); int getID(); signals: void finished(); }; .cpp:
#include "identificator.h" #include <stdio.h> identificator::identificator() { id=0; } identificator::~identificator() { // TODO Auto-generated destructor stub } void identificator::setID(int i) { id=i; } int identificator::getID() { return id; } void identificator::printID() { for(;;) { printf("%d\n",this->getID()); } emit finished(); } but main.cpp:
#include <QtCore> #include <QCoreApplication> #include <QApplication> #include "myThread.h" #include "identificator.h" #include <stdio.h> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); printf("Hello\n"); identificator *first=new identificator(); identificator *second=new identificator(); QThread *thread1=new QThread; QThread *thread2=new QThread; first->setID(3); second->setID(4); QObject::connect(thread1, SIGNAL(started()), first, SLOT(printID())); QObject::connect(thread2, SIGNAL(started()), second, SLOT(printID())); QObject::connect(first, SIGNAL(finished()), thread1, SLOT(quit())); QObject::connect(second, SIGNAL(finished()), thread2, SLOT(quit())); thread1->start(); thread2->start(); return a.exec(); } I expect that the numbers 3 and 4 will be displayed in the console, separately and indefinitely, but only 3 are displayed in the console when I start. Please, tell me how to get them to work in parallel? Thank you in advance!
I read that the algorithm should be something like this:
1) Create a stream. 2) Creating an object and transfer to the stream. 3) Installation of signal-slot communications. 4) Run a stream with a given priority.
Therefore added as advised: moveToThread ()
int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); printf("Hello\n"); identificator *first=new identificator(); identificator *second=new identificator(); QThread *thread1=new QThread; QThread *thread2=new QThread; first->setID(3); second->setID(4); first->moveToThread(thread1); second->moveToThread(thread2); QObject::connect(thread1, SIGNAL(started()), first, SLOT(printID())); QObject::connect(thread2, SIGNAL(started()), second, SLOT(printID())); QObject::connect(first, SIGNAL(finished()), thread1, SLOT(quit())); QObject::connect(second, SIGNAL(finished()), thread2, SLOT(quit())); thread1->start(); thread2->start(); return a.exec(); } Added moveToThread () and after initialization and after connect () both options did not help ....
I would be grateful for the help.