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

An icon of a clipboard-list1

You need to provide a working multithreading application using QThreadPool with QRunnable.

  1. Create a QRunnable subclass and implement its run() method with the code to execute in a background thread. QRunnable is not a QObject subclass, so it cannot have signals directly. You can easily work around this by creating a separate QObject subclass (named Signals here) and adding an instance to your QRunnable. In this example, run() emits Signals.progress and prints a message.
  1. In the main window, create a Runnable instance.

  2. Use QThreadPool.globalInstance() to access the global thread pool and QThreadPool.start() to execute Runnable.run() in one of its threads.

29.2 Walking the Filesystem

An icon of a clipboard-list1

Your task is to walk the filesystem using QThreadPool and QRunnable.

  1. Create a QRunnable subclass and implement run(). Add a member for signals and a boolean flag do_work for interruption. run() uses os.walk() to enumerate filesystem objects, emitting progress() for each while do_work is True.
  1. In the main window class, add a custom cancel_runnable() signal. Connect it to Runnable.on_cancel_emitted(), which sets Runnable.do_work to False.

  2. In on_start_button_clicked() create a Runnable object and connects signals to slots: progress updates the label; on cancel, emit cancel_runnable() to set do_work False.

  3. Access the global thread pool and run the task with QThreadPool.start().