29. Multithreading with QThreadPool and QRunnable
The QThreadPool class manages a collection of QThreads and is used with the QRunnable class.
29.1 A Minimal Example
![]() |
You need to provide a working multithreading application using |
- Create a
QRunnablesubclass and implement itsrun()method with the code to execute in a background thread.QRunnableis not aQObjectsubclass, so it cannot have signals directly. You can easily work around this by creating a separateQObjectsubclass (namedSignalshere) and adding an instance to yourQRunnable. In this example,run()emitsSignals.progressand prints a message.
In the main window, create a
Runnableinstance.Use
QThreadPool.globalInstance()to access the global thread pool andQThreadPool.start()to executeRunnable.run()in one of its threads.
29.2 Walking the Filesystem
![]() |
Your task is to walk the filesystem using |
- Create a
QRunnablesubclass and implementrun(). Add a member for signals and a boolean flagdo_workfor interruption.run()usesos.walk()to enumerate filesystem objects, emittingprogress()for each whiledo_workisTrue.
In the main window class, add a custom
cancel_runnable()signal. Connect it toRunnable.on_cancel_emitted(), which setsRunnable.do_worktoFalse.In
on_start_button_clicked()create aRunnableobject and connects signals to slots:progressupdates the label; on cancel, emitcancel_runnable()to setdo_workFalse.Access the global thread pool and run the task with
QThreadPool.start().
