QT5. There is a cycle from 0 to 1,000,000. At each iteration, you need to run the same “heavy” function, whose argument is the iteration number. I want to display the work of the function in a separate thread, but also to set some of their maximum number and timeout for launch. Let's say we have 10 threads. Work 2. Run the third after a timeout of 1 second. Etc. until the tenth. After starting the last free - timeout, and after waiting for the completion of any of the 10 threads - to start a new one. How to implement?
- oneQThreadPool any suitable, I think. True, I can not say anything about the pause before the launch of threads. - Vladimir Martyanov
- Can any example? - Oleg From
- When you need an example on using NNN, just type in Google "NNN example" and see what will be in the results. - Vladimir Martyanov
|
1 answer
You can do something like this, using the QtConcurrent and QThreadPool :
#include <QtCore/QThreadPool> #include <QtCore/QTimer> #include <QtConcurrent/QtConcurrent> class MyClass : public QObject { Q_OBJECT public: int maxThreads() {return _max_threads;} void setMaxThreads(int num) {_max_threads = num;} void start(); private: int _max_threads; void longRunMethod(int i) {/*...*/} }; void MyClass::start() { QThreadPool *pool = new QThreadPool(this); pool->setMaxThreadCount(1); for(int i = 0; i < 1000000; ++i) QtConcurrent::run(pool, this, &MyClass::longRunMethod, i); QTimer *timer = new QTimer(this); timer->setInterval(1000); timer->start(); connect(timer, &QTimer::timeout, [this,pool,timer]() { int threads_count = pool->maxThreadCount(); if(_max_threads > threads_count) return pool->setMaxThreadCount(++threads_count); timer->stop(); timer->deleteLater(); pool->waitForDone(); pool->deleteLater(); }); } The QtConcurrent::run(pool, this, &MyClass::longRunMethod, i) string QtConcurrent::run(pool, this, &MyClass::longRunMethod, i) does not immediately call the MyClass::longRunMethod() method, but only puts each of them in a queue. At first there will be only one stream, and after a second - two, then a pause again and there will be three, and so on.
- When compiling, the error is
C:\Users\Oleg.Skrobuk\Documents\Qt\Graph\untitled8\myclass.h:45: ошибка: no matching function for call to 'MyClass::connect(QTimer*&, void (QTimer::*)(QTimer::QPrivateSignal), MyClass::start()::<lambda()>)' });how to deal with it? - Oleg - The line
CONFIG += c++11added to the project file? - alexis031182
|