chao chao - 3 years ago 96
C++ Question

Qt multithreading: How to append few QRunnable tasks to QThreadPool

I am confused about how

QThreadPool
works, and can not find answer to it. I would like to have something like this:

class Task : public QRunnable { solve problem #nb }


Now, for example, I need to do 10 tasks which are not related and they does not share some values. I hope that I could do something like this:

QThreadPool pool;
pool.addTask(task1);
pool.addTask(task2);
pool.addTask(taskN);
pool.start();


For me, above example is a pool. I have few tasks, and I added to the pool and finally execute it all in each thread, but this is not how
QThreadPools
works. So, can I solve my problem using
QThreadPool
, or should I use something else?

Thank you.

Answer Source

Basically it works for your example like this (Note: I create the pool itself on the heap or it will be deleted at the end of the function scope)

pool = new QThreadPool(this);
pool->setMaxThreadCount (1);
pool->start(myQRunnablePtr1); 
pool->start(myQRunnablePtr2);
pool->start(myQRunnablePtr3);
// ...
pool->start(myQRunnablePtrN);

You could set the maxThreadCount higher if threads are allowed to run at the same time. In this example they will be executed in order of starting/queueing and the first has to end before the second will be run.

Additional you can add a priority to the start function, it you want to change the queueing later on. Lets say if you have a task that has to be started immediately.

The Class has some other use cases too (like tryStart) but this here might be enought for most cases.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download