#include <QThread.h>
Thread pools are an old & common invention used to work around the cost of creating and destroying a thread. They permit you to gain all the advantages of multi-threaded programming to a fine-grained level without many of the costs. Thus, they are ideal for when you regularly have small tasks to be carried out in parallel with the main execution.
Typically to send a job to a thread pool costs barely more than waking a sleeping thread. If there are no threads available (ie; they're all processing a job), the job enters a FIFO queue which is emptied as fast as the worker threads get through them. You furthermore can delay the execution of a job for an arbitrary number of milliseconds - thus a timed call dispatcher comes for free with this class.
Jobs can be waited upon for completion & cancelled. FX::FXProcess provides a process-wide thread pool which is created upon first-use - certain functionality such as the filing system monitor (FX::FXFSMonitor) use the process thread pool to run checks as well as dispatch notifications of changes.
FXProcess::threadPool().dispatch(Generic::BindFuncN(obj, method, pars));
Cancelling jobs with cancel() can get tricky. If it's a simple case of cancelling it before it has run, all is good and Cancelled
is returned. If the job is already running, you can optionally have cancel() wait until it's returned but in either case WasRunning
is returned (if the job completed, the functor is deleted as usual). Be aware that if your job reschedules itself, cancel() when returning WasRunning
won't actually have cancelled the job and you'll need to call it again. Suggested code is as follows:
while(QThreadPool::WasRunning==threadpool.cancel(job));
Definition at line 1228 of file QThread.h.
Public Types | |
typedef void * | handle |
typedef Generic::Functor< Generic::TL::create< bool, QThreadPool *, handle, DispatchUpcallType >::value > | DispatchUpcallSpec |
PreDispatch | |
PostDispatch | |
CancelledPreDispatch | |
NotFound | |
Cancelled | |
WasRunning | |
enum | DispatchUpcallType { PreDispatch, PostDispatch, CancelledPreDispatch } |
enum | CancelledState { NotFound, Cancelled, WasRunning } |
Public Member Functions | |
QThreadPool (FXuint total=FXProcess::noOfProcessors(), bool dynamic=false) | |
~QThreadPool () | |
FXuint | total () const throw () |
FXuint | maximum () const throw () |
FXuint | free () const throw () |
void | setTotal (FXuint newno) |
bool | dynamic () const throw () |
void | setDynamic (bool v) |
handle | dispatch (FXAutoPtr< Generic::BoundFunctorV > code, FXuint delay=0, DispatchUpcallSpec *upcallv=0) |
CancelledState | cancel (handle code, bool wait=true) |
bool | reset (handle code, FXuint delay) |
bool | wait (handle code, FXuint period=FXINFINITE) |