Last active
February 22, 2023 16:40
-
-
Save b-epelbaum/3035ac6b8c42a9157f3a6b44b2679af0 to your computer and use it in GitHub Desktop.
Fork-Join pattern in Qt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <QtCore> | |
| class MyTask : public QRunnable | |
| { | |
| public: | |
| MyTask(int id, int value) : m_id(id), m_value(value) {} | |
| void run() override | |
| { | |
| qDebug() << "Task" << m_id << "started with value" << m_value; | |
| // Perform some computation | |
| int result = m_value * 2; | |
| qDebug() << "Task" << m_id << "completed with result" << result; | |
| // Store the result for later retrieval | |
| m_result = result; | |
| } | |
| int getResult() const | |
| { | |
| return m_result; | |
| } | |
| private: | |
| int m_id; | |
| int m_value; | |
| int m_result; | |
| }; | |
| int main() | |
| { | |
| QThreadPool threadPool; | |
| threadPool.setMaxThreadCount(4); | |
| // Create tasks | |
| QList<MyTask*> tasks; | |
| for (int i = 0; i < 10; i++) { | |
| tasks.append(new MyTask(i, i + 1)); | |
| } | |
| // Submit tasks to the thread pool | |
| for (MyTask* task : tasks) { | |
| threadPool.start(task); | |
| } | |
| // Wait for tasks to finish | |
| threadPool.waitForDone(); | |
| // Collect results | |
| int sum = 0; | |
| for (MyTask* task : tasks) { | |
| sum += task->getResult(); | |
| } | |
| qDebug() << "Sum of results:" << sum; | |
| // Clean up tasks | |
| qDeleteAll(tasks); | |
| return 0; | |
| } | |
| int main() | |
| { | |
| // Create tasks | |
| QList<QFuture<void>> futures; | |
| for (int i = 0; i < 10; i++) { | |
| futures.append(QtConcurrent::run([i](){ | |
| qDebug() << "Task" << i << "started"; | |
| // Perform some computation | |
| QThread::msleep(1000); | |
| qDebug() << "Task" << i << "completed"; | |
| })); | |
| } | |
| // Wait for a specific task to complete | |
| QFuture<void>& futureToWaitFor = futures[3]; | |
| futureToWaitFor.waitForFinished(); | |
| qDebug() << "Task" << 3 << "has completed"; | |
| // Wait for all tasks to finish | |
| QFuture<void> allFutures = QtConcurrent::mapped(QList<QFuture<void>>(futures), [](const QFuture<void>& future) { | |
| return future; | |
| }); | |
| allFutures.waitForFinished(); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment