Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Threads, QRunnable and QThreadPool, I can't fit in the details

I know the general theory, Thread, QRunnable and QThreadPool. How does it all fit in ? I mean when an instance of QRunnable is created, and assigned to the ThreadPool, what does it mean to start a thread ? Can multiple threads access the same QRunnable ? Does one QRunnable necessarily map one-to-one with one worker thread ?

like image 302
Vishnu Pedireddi Avatar asked Mar 15 '11 18:03

Vishnu Pedireddi


1 Answers

QRunnable encapsulates a task that you want performed in a separate thread. If you need to know which thread is running that task or share it between threads, then you are probably doing something more complicated than what QThreadPool is designed to empower. In that case, you would create custom behavior using QThread directly. "Starting" a QRunnable with a QThreadPool is analogous to queueing that task for an available thread in the pool. Whereas, starting a QThread actually allocates a new OS thread and executes it.

The thread pool will manage a finite number of threads with a work queue of QRunnable instances. As a thread becomes available, it will be assigned a QRunnable to process. You don't need to explicitly create any QThread instances if you are using QThreadPool with QRunnable. Note that you still must ensure that shared resources are synchronized (e.g. with a QMutex, QMutexLocker, QReadWriteLock, QSemaphore, and/or QWaitCondition) when used in QRunnable instances.

like image 94
Judge Maygarden Avatar answered Sep 28 '22 12:09

Judge Maygarden