Example for Parallel Programming in Qt
-
Hi I am a beginner in Qt and while i was browsing about parallel programming in Qt to keep GUI responsive if a task more than normal time i.e 5sec i found this link
https://doc.qt.io/archives/qq/qq27-responsive-guis.html
I need a simple example to understand about Parallel Programming in Qt.
Please help me. -
Hi and welcome
Use the worker approach
https://john.nachtimwald.com/2015/05/02/effective-threading-using-qt/
https://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/Minimal code. Something like.
class Task : public QObject { Q_OBJECT public: Task(){}; ~Task(){}; public slots: void doWork(); signals: void workFinished(); }; QThread* thread = new QThread( ); Task* task = new Task(); task->moveToThread(thread); connect( thread, SIGNAL(started()), task, SLOT(doWork()) ); connect( task, SIGNAL(workFinished()), thread, SLOT(quit()) ); //automatically delete thread and task object when work is done: connect( thread, SIGNAL(finished()), task, SLOT(deleteLater()) ); connect( thread, SIGNAL(finished()), thread, SLOT(deleteLater()) ); thread->start(); void Task::doWork() { static int cc = 0; while(1) { // ugly qDebug() << "alive:" << cc++; } }
Note there is also qtconcurrent
http://doc.qt.io/qt-5/qtconcurrent-runfunction-main-cpp.htmlSo it depends on what you need. :)
Notice that Qt does not come with beginner documentation on Threads
That you must already know some about.
http://doc.qt.io/qt-5/thread-basics.html -
Hi and welcome
Use the worker approach
https://john.nachtimwald.com/2015/05/02/effective-threading-using-qt/
https://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/Minimal code. Something like.
class Task : public QObject { Q_OBJECT public: Task(){}; ~Task(){}; public slots: void doWork(); signals: void workFinished(); }; QThread* thread = new QThread( ); Task* task = new Task(); task->moveToThread(thread); connect( thread, SIGNAL(started()), task, SLOT(doWork()) ); connect( task, SIGNAL(workFinished()), thread, SLOT(quit()) ); //automatically delete thread and task object when work is done: connect( thread, SIGNAL(finished()), task, SLOT(deleteLater()) ); connect( thread, SIGNAL(finished()), thread, SLOT(deleteLater()) ); thread->start(); void Task::doWork() { static int cc = 0; while(1) { // ugly qDebug() << "alive:" << cc++; } }
Note there is also qtconcurrent
http://doc.qt.io/qt-5/qtconcurrent-runfunction-main-cpp.htmlSo it depends on what you need. :)
Notice that Qt does not come with beginner documentation on Threads
That you must already know some about.
http://doc.qt.io/qt-5/thread-basics.html