Working with 2 Threads
-
Hi everyone. Im working with threads. In the following code, i read datas from txt and run it on my thread. I want to use another thread for writing the datas another txt file. How can i do it?
#include "mythread.h" #include <QtCore> #include <QDebug> #include <QFile> MyThread::MyThread() { } void MyThread::run() //Reading file from txt with thread1 { QFile file("C:/Users/ilknu/Documents/untitled1/deneme.txt"); if (file.open(QIODevice::ReadOnly)) { QTextStream in (&file); while (!in.atEnd()) { QString line = in.readLine(); QStringList list = line.split(QLatin1Char(' '), Qt::SkipEmptyParts); for(const QString &entry : list) { double num = entry.toDouble(); qDebug()<<num; queue.enqueue(num); } // for } // while } // if file.close(); } -
Hi,
Based on your other questions with regard to your application, please do not start with threading now. It's a really complex and involved topic that you do not need most of the time.
Stay single threaded until you have more experience with C++ and also with the asynchronous nature of Qt.
-
Hi,
Based on your other questions with regard to your application, please do not start with threading now. It's a really complex and involved topic that you do not need most of the time.
Stay single threaded until you have more experience with C++ and also with the asynchronous nature of Qt.
@SGaist It sounds nice and make sense but i must work in any case
-
@SGaist It sounds nice and make sense but i must work in any case
@suslucoder said in Working with 2 Threads:
It sounds nice and make sense but i must work in any case
What do you mean by any case ?
-
There is a helpful video on youtube for learning
QThread.
https://www.youtube.com/watch?v=JaGqGhRW5Ks&t=299s&ab_channel=VoidRealms
I usually do not do it like that though.
I create an object and the thread as separate objects, then I useQObject::moveToThread, thenQThread::start, and connect signal slots to the object.Alternatively you can use
QtConcurrent::runwhich is easier to use.
https://doc.qt.io/qt-5/qtconcurrent.html
Call the function in aQtConcurrent::run, you can connect signal/slots to the returnedQFutureto a function that will execute once finished.