Solved how to pass periodically changed variables in new thread?
-
in main thread, i have used timers to do some calculation, and some(a little more) variables changed periodically, and because the output those variables to stdout cost time, so i want use new thread to out put them.
but what is the correct way to achieve this? i have read this article How To Really, Truly Use QThreads; The Full Explanation. it seems like to pass parameters at first into the work class, but still don't know how to pass changed variable into thread for doing something.
Accroding to qt document, Customer a new thread or new work class , which one is the correct way to achieve my goal?
-
So first you create your worker object, for example:
class Writer : public QObject { Q_OBJECT public slots: void write(const QString& stuff) { std::cout << stuff.toUtf8().constData(); std::cout.flush(); } };
Then you create a thread object, worker object, move the worker to that thread and start the thread:
QThread* thread = new QThread(some_parent); //create the thread Writer* writer = new Writer; //create the worker (no parent so you can move it) writer->moveToThread(thread); //move worker to the thread connect(thread, &QThread::finished, writer, &Writer::deleteLater); //delete the worker when thread quits thread->start(); //start the thread
Now connect the worker to some signal that you emit when you need to write something:
connect(somethingThatProducesMessages, &SomeObject::messageProduced, writer, &Writer::write);
Then you just need to stop the thread at some point:
thread->quit(); thread->wait();
-
@Chris-Kawa thanks for your answer. it really helps me!